# Need help in explaining passing an array to a function

• 03-04-2013
ntdvs
Need help in explaining passing an array to a function
Please refer to the following code:

Code:

#include <stdio.h>

#define MAX 10

int array[MAX+1], count;

int largest(int num_array[]);

int main( void )
{
for (count = 0; count < MAX; count++)
{
printf("Enter an integer value: ");
scanf("%d", &array[count]);

if ( array[count] == 0 )
count = MAX;
}
array[MAX] = 0;

printf("\n\nLargest value = %d\n", largest(array));

return 0;
}

int largest(int num_array[])
{
int count, biggest = -12000;

for ( count = 0; num_array[count] != 0; count++)
{
if (num_array[count] > biggest)
biggest = num_array[count];
}

return biggest;
}

Can anybody please explain how the for loop at the largest() function searches for the largest number entered in the array?

Thanks.
• 03-04-2013
Click_here
Global variables are initialised to 0 and the last element of the array is preserved as 0 (note that this is means that the user may not enter 0, so it appears to be flawed program)

The for loop goes through the array until the 0 is found, replacing the variable "biggest" with any number it finds that is bigger than the current value in " biggest"

I think that the program should either pass a parameter of the array size, or make use of the define MAX.
• 03-04-2013
hex_dump
Personally I find the random function very helpful when working with integer arrays and trying to understand them. I second Click_here's answer and recommendation. Have a look at this code, play around with the SIZE and RAND symbolic constants and see what it outputs.
Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 25
#define RAND 251

int find_largest(int*, int);

int main(void){

srand(time(NULL));
int storage[SIZE];

int i;
int j;
printf("The contents of the array: ");
for(i=0;i<SIZE; i++){
j =(rand() % RAND );
storage[i] = j;
printf("%2.2d...\n", *(storage + i) );
}

printf("\nFinally the largest int is %2.2d...\n", find_largest(storage, SIZE) );

return 0;
}

int find_largest(int* the_array, int elements){

int cur;
int largest;
largest = the_array[0];
printf("Initially the largest is %2.2d..\n", largest);

for(cur = 1; cur < elements; cur++){
if(the_array[cur] > largest){
largest = the_array[cur];
printf("The largest is now %2.2d...\n", largest);
}
}

return largest;

}