90 likes | 111 Views
Learn how to pass individual array elements, entire arrays, and multidimensional arrays to functions in programming. Understand the concepts of pass by value and pass by reference.
E N D
Programming Passing Arrays to Functions
Array Element Pass by Value • Individual array elements can be passed by value or by reference • Pass-by-value example: void printcard(int c) { if(c==1) cout << "A"; ... } void main() { int cards[5] ; ... for(int n=0; n<5; n++) printcard(card[n]); }
Array Element Pass by Reference • Pass-by-reference example: void swap(int& x, int& y) { int temp; if (x > y){ temp = x; x = y; y = temp; } } void main() { int A[10] = {9,8,7,6,5,4,3,2,1,0}; swap(A[3], A[5]); }
Array Element Pass by Reference • Before: • After:
Passing Entire Arrays to Functions • Arrays can be passed to functions in their entirety. • All that is required is the address of the first element and dimensions of the array. • The remainder of the array will be passed by reference automatically.
Arrays to Functions: Example 1 //Find the largest value in an array //input: n - number of elements to check // a[ ] - array of elements // output:index to the largest element #include <iostream> using namespace std; int max_element(int n, const int a[]) { int max_index = 0; for (int i=1; i<n; i++) if (a[i] > a[max_index]) max_index = i; return max_index; } void main() { int A[10] = {9,8,7,6,5,4,10,2,1,0}; cout << A[max_element(10,A)] << endl; }
Arrays to Functions: Example 2 //Add a[i] and b[i] and store the sum in c[i] //Array elements with subscripts ranging from //0 to size-1 are added element by element void add_array(int size, const double a[], const double b[], double c[]){ for (int i=0; i<size; i++) c[i] = a[i] + b[i]; } In main(): add_array (5, x, y, z );
Passing Multidimensional Arrays • How to pass a multidimensional array to a function: void displayBoard(int b[][4]); // function prototype requires variable name for arrays void main(){ int board [4][4]; ... displayBoard(board); ... } void displayBoard(int b[][4]){ // could also be: void displayBoard(int b[4][4]){ // but NOT: void displayBoard(int b[][]){ ... } • When passing a multidimensional array, only the size of the 1st dimension is optional, the 2nd, 3rd, etc. dimensions must be specified.