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
Related Posts:
- Data Types in C++
- Operators in C++
- Recursion in C++ with example
- Functions in C++ with example
- goto statement in C++ with example
- Break statement in C++ with example
- Continue Statement in C++ with example
- do-while loop in C++ with example
- While loop in C++ with example
- For loop in C++ with example
- Switch Case statement in C++ with example
- If else Statement in C++
- Constructors in C++
- Enumeration in C++
- OOPs Concepts in C++
- this pointer in C++
- Pointers in C++
- Strings in C++
- Multidimensional Arrays in C++
- Arrays in C++
- Difference between Function Overloading and Function overriding in C++
- Function Overriding in C++ with examples
- Function overloading in C++ with examples
- Polymorphism in C++ and its types
- Inheritance in C++ with examples
- Destructors in C++ with examples
- Encapsulation in C++ with example
- Friend Class and Friend Functions in C++
- Interfaces in C++ with Examples
- Abstraction in C++ with example