Arrays can be passed
down to functions like other single variables. We use them by their name
as arguments when we call the function. The parameter list of the function
must indicate the fact that a parameter is an array by augmenting the
[ ] at the end of the one dimensional arrays. In one-dimensional arrays
the actual size does not have to be given. In case of two-dimensional
arrays we recommend that you give the size of the array in both dimensions.
NOTE: Arrays are always
passed by name. In other words if we change the array in the function,
then this change reflects back to the calling function. Read the explanations provided for the example . |
|
/* |
|
The function has five parameters. The first four are single variables passed by value. The fifth parameter is an array. As we mentioned earlier, arrays are passed by name. |
/* function prototypes */ |
ofstream out( "6ex3rep.txt" , ios:: out); |
|
The variables are declared and the regular variables a, b, c, d are initialized one by one. |
float a, b, c, d; |
The array can be initialized using a loop |
for ( i = 0; i <= 3; i++) |
Values of the variables are printed out to the file called 6ex3rep.txt via the stream out, before the call to the function. We do this so that we can compare these values to the ones after the call. |
Print before you call the function */ |
The function is called. Notice that the array goes in the argument list with only its name ( no brackets). |
/***************************************** |
Values of the variables are printed out to the file called 6ex3rep.txt via the stream out, after the call to the function |
/* Print after you call the function */ |
This is the definition of the function. The task of the function is to calculate the squares of all variables |
void square_them( float a, float b, float c, float d, float u[]) |
We print the values from within the function. Thus we are going to have
three printings: a) before the call b) from the function c) after the call |
/* Print from within the function */ |
Note the following: Before the call to the function we have the values which we assigned. From within the function square_them, we get the squares of all variables From the function main when we print the variables after the call to the function square_them we get the "unsquared " values for a, b, c, d but the squared values for the array elements. This is because the single variables a, b, c, d are passed by valu( no & is placed before them) but the array always passes by name. |
THE OUTPUT IS: |
(text file of the above code - 6ex3)
© 2001 J.Y. Kazakia. All rights reserved