Lec 14 - Lec 14 Arrays as Arguments Arrays as Arguments ►...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lec 14 Oct 23, 02 Arrays as Arguments 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. Passing whole array as argument 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 Other examples Other examples // Array declarations int nums[5]; int char keys[256]; char double volts[500], current[500]; double ► // function calls // find_max(nums) find_max(nums) find_ch(keys) find_ch(keys) calc_tot(nums, volts, current) calc_tot(nums, ► // function headers int find_max(int vals[5]) char find_ch(char in_keys[256]) char void calc_tot( int arr1[5], double arr2[500], double arr3[500] ) void / * The parameter list in the function header still refer to the original The array created outside the function. */ array ► ► #include<iostream.h> Example 1 Example 1 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; } Example 1 function 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; } Alternative function header Alternative function header ► int find_max( int vals) instead of int find_max(int vals[MAXELS]); Example 2 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; } Example 2 function 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; } 2­D arrays 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]) ► Alternative function header for 2­D arrays Alternative function header for 2­D arrays ► display(int nums[4]); ...
View Full Document

This document was uploaded on 07/06/2011.

Ask a homework question - tutors are online