# Thread: function for largest value

1. ## function for largest value

If i want to find largest number in any sequence, I write program like this

Code:
``` #include<stdio.h>

int main()
{
int i = 0;
int array[5] = {1, 2, 3, 4, 5};
int largest = array[i];

for (i = 1; i <= 5; i++)
{
if ( largest < array[i])
largest = array[i];
}

printf(" largest : %d ", largest);
return 0;

}```
I want to make a function that gives largest number. I don't know how to do it using function

Code:
```#include<stdio.h>

void foo( int *ptr)
{
int largest = *ptr;
for (i = 1; i <= 5; i++)
{

}
printf(" largest : %d ", largest);
}
int main()
{
int i = 0;
int array[5] = {1, 2, 3, 4, 5};
foo(&array[0]);

return 0;

}```

2. > for (i = 1; i <= 5; i++)
Well the first step is knowing how to loop over an array.
The test should be <, not <=

Compare
Code:
```#include<stdio.h>

int main()
{
int i = 0;
int array[5] = {1, 2, 3, 4, 5};
int largest = array[i];

for (i = 1; i < 5; i++)
{
if ( largest < array[i])
largest = array[i];
}

printf(" largest : %d ", largest);
return 0;

}```
with
Code:
```#include<stdio.h>
int largestValue(int array[]) {
int i = 0;
int largest = array[i];

for (i = 1; i < 5; i++)
{
if ( largest < array[i])
largest = array[i];
}
return largest;
}

int main()
{
int array[5] = {1, 2, 3, 4, 5};
int largest = largestValue(array);
printf(" largest : %d ", largest);
return 0;
}```
You don't need to alter any of the code, you can just copy/paste the loop body directly into a function.
Not a single * to be seen.

3. Thank you very much

4. If you need to do this in a function because you want to use arbitrary sized arrays, the number of elements in the array must be passed to the function:
Code:
```// return the position with the largest value
// or -1 if elems == 0.
unsigned int find_largest_int( int *p, unsigned int elems )
{
unsigned int i, j;

if ( ! elems ) return -1;

for ( j = 0, i = 1; i < elems; i++ )
if ( p[i] > p[j] )
j = i;

return j;
}```
Example:
Code:
```  int array[] = { 1, 2, 3, 7, 5, 6 };
unsigned int largest;

largest = find_largest_int( array, sizeof array / sizeof array[0] );

// don't need to test for 'largest == (unsigned int)-1' because the array has elements...
printf( "Found @%u: %d\n", largest, array[largest] );```