138 Chapter 8 Working with Functions
function to display the elements of an array), the array element is specified as an argu-
ment to the function in the normal fashion. So, to take the square root of averages[i]
and assign the result to a variable called sq_root_result,a statement such as
sq_root_result = squareRoot (averages[i]);
does the trick.
Inside the squareRootfunction itself, nothing special has to be done to handle single
array elements passed as arguments. In the same manner as with a simple variable, the
value of the array element is copied into the value of the corresponding formal parame-
ter when the function is called.
Passing an entire array to a function is an entirely new ball game.To pass an array to a
function, it is only necessary to list the name of the array,without any subscripts, inside the
call to the function. As an example, if you assume that gradeScoreshas been declared as
an array containing 100 elements, the expression
minimum (gradeScores)
in effect passes the entire 100 elements contained in the array gradeScoresto the func-
tion called minimum.Naturally, on the other side of the coin, the minimumfunction must
be expecting an entire array to be passed as an argument and must make the appropriate
formal parameter declaration. So the minimumfunction might look something like this:
int minimum (int values[100])
{
...
return minValue;
}
The declaration defines the function minimumas returning a value of type intand as
taking as its argument an array containing 100 integer elements. References made to the
formal parameter array valuesreference the appropriate elements inside the array that
was passed to the function. Based upon the function call previously shown and the cor-
responding function declaration, a reference made to values[4], for example, would
actually reference the value of gradeScores[4].
For your first program that illustrates a function that takes an array as an argument,
you can write a function minimumto find the minimum value in an array of 10 integers.
This function, together with a mainroutine to set up the initial values in the array, is
shown in Program 8.9.
Program 8.9 Finding the Minimum Value in an Array
// Function to find the minimum value in an array
#include <stdio.h>