In C++, passing an array to a function in the one-Dimensional array is done through an actual parameter and array variables with subscript are passed as formal arguments. While passing the array only the name of the array is passed to the function.
Same method is applied for the multi-dimensional array.
The syntax for passing an array to a function: There are three methods that can be used to pass an array to a function.
First Way: As a unsized array
1 2 3 4 | return_type function(type arrayname[]) { ..... } |
Second Way: As a sized array
1 2 3 4 | return_type function(type arrayname[SIZE]) { ..... } |
Third Way: As a pointer
1 2 3 4 | return_type function(type *arrayname) { ..... } |
C++ Program for Passing One-dimensional Array to a Function
The following program find the sum of all the numbers present in an array of one-dimensional.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // C++ Program to find the sum of all the numbers #include <iostream> using namespace std; // function to add and return result int sumFunc(int arr[], int size) { int sum = 0; for (int i = 0; i < size; ++i) sum += arr[i]; return sum; } int main() { // declaring and initializing an array int num_array[5] = { 20, 55, 18, 68, 10 }; int result; //aclling a function by passing array and size result = sumFunc(num_array, 5); cout << "The sum of all numbers: " << result << endl; return 0; } |
Output:
1 | The sum of all numbers: 171 |
C++ Program for Passing Multidimensional Array to a Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | // C++ Program to display the 2D array elements #include <iostream> using namespace std; void displayFunc(int arr[][2], int row, int col) { cout << "Elements present in an Array: " << endl; for (row = 0; row < 3; ++row) { for (col = 0; col < 2; ++col) { cout << "arr[" << row << "][" << col << "]: " << arr[row][col] << endl; } } } int main() { // initialize 2d array int num[3][2] = { { 6, 9 }, { 5, 4 }, { 3, 2 } }; // call the function displayFunc(num, 3, 2); return 0; } |
Output:
1 2 3 4 5 6 7 | Elements present in an Array: arr[0][0]: 6 arr[0][1]: 9 arr[1][0]: 5 arr[1][1]: 4 arr[2][0]: 3 arr[2][1]: 2 |
Note: It is mandatory to give the column value in formal parameters but it is not necessary to give a row value. That is why int arr[][2]
is written. We inserted 2 in the column value.