Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lec 14 Oct 23, 02.

Similar presentations


Presentation on theme: "Lec 14 Oct 23, 02."— Presentation transcript:

1 Lec 14 Oct 23, 02

2 Arrays as Arguments Individual array elements are passed to a called function in the same manner as individual scalar variables. eg: find_min(volts[2], volts[6]); passes the values of the elements volts[2] and volts[6] to the function find_min.

3 Passing whole array as argument
Passing a complete array of values to a function is in many respects an easier operation than passing individual elements. The called function receives access to the actual array, rather than copy of the values in the array. Eg: find_max(volts); makes the complete volts array available to the find_max function

4 Other examples // Array declarations int nums[5]; char keys[256];
double volts[500], current[500]; // function calls find_max(nums) find_ch(keys) calc_tot(nums, volts, current) // function headers int find_max(int vals[5]) char find_ch(char in_keys[256]) void calc_tot( int arr1[5], double arr2[500], double arr3[500] ) / * The parameter list in the function header still refer to the original array created outside the function. */

5 #include<iostream.h>
Example 1 #include<iostream.h> const int MAXELS = 5; int find_max(int [MAXELS]);// function prototype declaration int main() { int nums[MAXELS] = {2, 18, 1, 27, 16}; cout<< “The maximum is “<<find_max(nums) <<endl; return 0; }

6 int find_max(int vals[MAXELS])
Example 1 function int find_max(int vals[MAXELS]) { int i, max = vals[0]; for (i=1; i<MAXELS; i++) if (max<vals[i] ) max = vals[i]; return max; }

7 Alternative function header
int find_max( int vals[]) instead of int find_max(int vals[MAXELS]);

8 Example 2 #include<iostream.h>
int find_max(int [], int); //function prototype int main() { const int MAXELS = 5; int nums[MAXELS] = {2, 18, 1, 27, 16}; cout<<“ The maximum value is “ <<find_max(nums, MAXELS) <<endl; return 0; }

9 int find_max(int vals[], int num_els)
Example 2 function int find_max(int vals[], int num_els) { int i, max = vals[0]; for(i=1; i< num_els; i++) if (max<vals[i]) max = vals[i]; return max; }

10 2-D arrays int test[7][9]; // array declaration float factors[26][10];
double thrusts[256][52]; find_max(test); // function calls obtain(factors); average(thrusts); int find_max(int nums[7][9]) // function header int obtain(float values[26][10]) int average(double vals[256][52])

11 Alternative function header for 2-D arrays
display(int nums[][4]);


Download ppt "Lec 14 Oct 23, 02."

Similar presentations


Ads by Google