Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Urgent help needed..function passing argument (http://www.go4expert.com/forums/urgent-help-neededfunction-passing-t6631/)

ikik84 1Oct2007 00:58

Urgent help needed..function passing argument
 
hi all.


i'm newbie for c-prog,
in school, given question

Finding the Smallest Value (small.c)
(a) Write a function, smallest( ), that returns the smallest value in a signed integer
array. The array and its size are passed as arguments.

(b) Write a main program that inputs MAX values from the keyboard into a signed
integer array, array, and prints, using smallest( ), the smallest value to the screen


currently my find the smallest loop and passing argument seens like not correct.
able to compile and run...but result not correct...can somebody kindly enlighten me plz... :confused:




Code:

/*Small.c*/

#include<stdio.h>


#define MAX  4

int smallest(int num[], int size);


main()
 {
        int n,i,y,h;
        int num[20];

        for(i=0;i<MAX;i++)
        {
        printf("Please enter number:");
        scanf("%d", &num[i]);
        /*printf("%d", num[i]);  test for input */
        }

        h=smallest(num,sizeof num);
        printf("The smallest number is %d",h);

        getch();

}

int smallest(int *num,int size)
 {


        int j,i;


        for(j=0;j<MAX;j++)
        {



        /*find smallest */
        for(i=0;i< (num[i]-1);i++)
        {                size= i;

                for(j = i+1; j<MAX; j++)
                { if(num[j] <num[size])
                        size=j;
                        }
        printf("%d\n",i);


        }
        printf("%d",size);




}


}


DaWei 1Oct2007 01:16

Re: Urgent help needed..function passing argument
 
You have a number of issues. This does not do as you expect:
Code:

    h=smallest(num,sizeof num);
num is a pointer to the array. Sizeof num is merely the size of a pointer, not the size of the array. If you get MAX entries, pass MAX as the size. You need to make sure you get MAX entries, though. Input can fail. Suppose the user enters 'A' instead of a number. You're screwed without ever being kissed. Always check your input functions for success. See scanf and its return value for details.

Once you get into the "smallest" function, set up a loop that runs from 0 to size-1. Put the first value into a variable. Compare each following value to the variable. If it's smaller, put it in the variable. If not, just go on to the next. When you're through, return the variable.


All times are GMT +5.5. The time now is 09:11.