FREE E LEARNING PLATFORM
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Passing Array to Function in C++


You can pass array as an argument to a function just like you pass variables as arguments. In order to pass array to the function you just need to mention the array name during function call like this:

function_name(array_name);

Example: Passing arrays to a function

In this example, we are passing two arrays a & b to the function sum(). This function adds the corresponding elements of both the arrays and display them.
#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: Passing multidimensional array to function

In this example we are passing a multidimensional array to the function square which displays the square of each element.

#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

noidatut course







Leave Comment