Passing Array to Function in C++

Passing Array to Function in C++

You’ll be able to cross arrays an argument to a operate similar to you cross variables as arguments. With a view to cross array to the operate you simply must point out the array identify throughout operate name like this:

 

function_name(array_name); 

Instance: Passing arrays to a operate

On this instance, we’re passing two arrays a & b to the operate sum(). This operate provides the corresponding components of each the arrays and show them.

 

#embrace 
utilizing namespace std;
/* This operate provides the corresponding
 * components of each the arrays and
 * shows it.
 */
void sum(int arr1[], int arr2[]){
   int temp[5];
   for(int i=0; i<5; i++){
      temp[i] = arr1[i]+arr2[i];
      cout<<temp[i]<<endl;
   }
}
int major(){
   int a[5] = {10, 20, 30, 40 ,50};
   int b[5] = {1, 2, 3, 4, 5};
   //Passing arrays to operate
   sum(a, b);
   return 0;
}

output:

 

11
22
33
44
55

Instance 2: Passing multidimensional array to operate

On this instance we’re passing a multidimensional array to the operate sq. which shows the sq. of every factor.

#embrace 
#embrace 
utilizing namespace std;
/* This technique prints the sq. of every
 * of the weather of multidimensional array
 */
void sq.(int arr[2][3]){
   int temp;
   for(int i=0; i<2; i++){
      for(int j=0; j<3; j++){
        temp = arr[i][j];
        cout<<pow(temp, 2)<<endl;
      }
   }
}
int major(){
   int arr[2][3] = { 
       {1, 2, 3},
       {4, 5, 6}
   };
   sq.(arr);
   return 0;
}

Output:

 

1
4
9
16
25
36