Programming in C

(Barry) #1
Functions and Arrays 141

Program 8.10 Revising the Function to Find the Minimum Value in an Array


// Function to find the minimum value in an array


#include <stdio.h>


int minimum (int values[], int numberOfElements)
{
int minValue, i;


minValue = values[0];

for ( i = 1; i < numberOfElements; ++i )
if ( values[i] < minValue )
minValue = values[i];

return minValue;
}


int main (void)
{
int array1[5] = { 157, -28, -37, 26, 10 };
int array2[7] = { 12, 45, 1, 10, 5, 3, 22 };
int minimum (int values[], int numberOfElements);


printf ("array1 minimum: %i\n", minimum (array1, 5));
printf ("array2 minimum: %i\n", minimum (array2, 7));

return 0;
}


Program 8.10 Output


array1 minimum: -37
array2 minimum: 1


This time, the function minimumis defined to take two arguments: first, the array whose
minimum you want to find and second, the number of elements in the array.The open
and close brackets that immediately follow valuesin the function header serve to
inform the C compiler that valuesis an array of integers. As stated previously, the com-
piler really doesn’t need to know how large it is.
The formal parameter numberOfElementsreplaces the constant 10 as the upper limit
inside the forstatement. So the forstatement sequences through the array from values[1]
through the last element of the array, which is values[numberOfElements - 1].

Free download pdf