Arguments in a function can also be of array type. When the arrays are passed by value in a function, it is written as shown in the following example:
float f1(int* c, int* d){} void main() { int c[5]; int d[4]; f1(c, d); }
Example
The program illustrates merging two arrays using Merge sort. Two or more sorted arrays are given as input for merge sort. The procedure is explained below when two sorted arrays X and Y are given as input. The array X has m elements and the array Y has n elements. Z is the newly created array. The algorithm is as follows:
if(x<sub>i</sub><y<sub>j</sub>) { Z<sub>k</sub>=X<sub>i</sub> increment i and k } else { if (Y<sub>j</sub><X<sub>i</sub>) Z<sub>k</sub> = Y<sub>j</sub> increment j and k } else if (X<sub>i</sub> = Y<sub>j</sub>) { Z<sub>k </sub>= X<sub>i</sub> Z<sub>k+1</sub>= Y<sub>j</sub> increment i, j and k }
The program uses call by value function.
#include<iostream.h> const int size = 10; void merge(int* a, int* b) { int i=0,j=0,k=0,I=0; int c[10]; while(i<5 && j<5) { if(a[i] < b[j]) { c[k]=a[i] ; i++; k++; } else if(b[j]<a[i]) { c[k]=b[j]; j++; k++; } else { c[k]=a[i] ; k++; c[k]=b[j]; k++; i++; j++; } } for(I=i;I<5;I++) { c[k]=a[I]; k++; } for(I=j ;i<5;I++) { c[k]=b[I]; k++; } cout<<"\nSorted array: "; for(k=0;k<10;k++) cout<<c[k]<<" "; } void main() { int a[5]; int b[5]; int c[10]; cout<<"Enter the sorted values for first array"; for(int i=0;i<5;i++) cin>>a[i]; cout<<"\nEnter the sorted values for second array"; for(i=0;i<5;i++) cin>>b[i]; merge( a,b); }
When the arrays are passed by reference to a function, it is written as follows :
float f1(int* c, int* d) { void main() { int c[5]; int d[4]; fi(c, d); }
In this case, the address of c and d are given as arguments in the function.
Example
Following is an example to illustrate two dimensional array passed as reference.
#include <iostream.h> void Transpose(int** &); const m=3, n=3; void main() { int i, j; int **A;//Pointer to pointer to int A = new int* [m]; for(i=0;i<m;i++ ) A[i] = new int[n];//An mxn Matrix // A[i] is a pointer to row of int for(i=0;i<m;i++ ) for(j=0;j<n;j++ ) { cout<<" A["<<i<<", "<<j<<"] = "; cin>>A[i][j]; } for(i=0;i<m;i++ ) { for(j=0;j<n;j++ ) cout<<" " <<A[i][j]; cout<<endl; } Transpose(A); cout<< endl<<"Transpose of the matrix is: "<<endl; for(i=0;i<m;i++ ) { for(j=0;j<n;j++) cout<<A[i] [j]<<" "; cout<<endl; } } void Transpose(int** &a) { int i,j,t; for (i=0;i<m;i++) for(j=0;j<i;j++ ) { t=a[i][j]; a[i][j] = a[j][i]; a[j] [i] = t; } }