Passing Arrays to Functions:
Passing One-Dimensional Arrays:
Like the values of simple variables, it is also possible to
pass the values of an array to a function. To pass a one-dimensional an array
to a called function, it is sufficient to list the name of the array, without
any subscripts, and the size of the array as arguments. For example, the call
largest (a,n)
will pass the whole array a to the called function. The called function expecting this call
must be appropriately defined. The largest
function header might look like;
float largest (float array[ ], int size)
The function largest is
defined to take two arguments, the array name and the size of the array to
specify the number of elements in the array. The declaration of the formal
argument array is made as follows:
float array [ ];
The pair of brackets informs the compiler that the argument array is an array of numbers. It is not
necessary to specify the size of the array
here.
Passing
Two-Dimensional Arrays:
Like simple arrays, we can also pass muli-dimensional arrays
to functions. The approach is similar to the one we did with one-dimensional
arrays. The rule is simple.
1. The
function must be called by passing only the array name.
2. In
the function definition, we must indicate that the array has two-dimensions by
including two sets of brackets.
3. The
size of the second dimension must be specified.
4. The
prototype declaration should be similar to the function header.
The function given below calculates the average of the values in a two-dimensional matrix.
double average(int
x[ ] [n], int m, int n)
{
int i,j;
double sum =0.0;
for (i=0;i<m;i++)
for
(j=1;j<n;j++)
sum += x [i] [j];
return ( sum/(m*n));
}
Post a Comment