C++

In C++, Passing An Array To A Function – Q&A

Like passing variables as arguments, you can also pass an array as an argument to a function. You only need to mention the array name during the function call in the following way to pass an array to the function:

function_name(array_name);

As an illustration, pass arrays to a function.

In this case, the function sum is given two arrays, a and b. (). This function displays and adds the corresponding elements from both arrays.

#include <iostream>
using namespace std;
/* This function adds the corresponding
 * elements of both the arrays and
 * displays 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 main(){
   int a[5] = {10, 20, 30, 40 ,50};
   int b[5] = {1, 2, 3, 4, 5};
   //Passing arrays to function
   sum(a, b);
   return 0;
}

Output:

11
22
33
44
55

Example 2: Invoking a function with a multidimensional array

This example uses the function square to display the square of each element from a multidimensional array.

#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
 * of the elements of multidimensional array
 */
void square(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 main(){
   int arr[2][3] = { 
       {1, 2, 3},
       {4, 5, 6}
   };
   square(arr);
   return 0;
}

Output:

1
4
9
16
25
36

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button