Function and array in C++

Function and array in C++

To pass an array to function in C++, we have to provide only array name. Pass the array as an argument to a function similar to variables as arguments.

Syntax for Passing Arrays as Function Parameters

returnType functionName(dataType arrayName[arraySize]) {
    // code
}

Example of Passing Arrays as Function Parameters

int total(int marks[5]) {
    // code
}

Program of Passing Arrays as Function Parameters

#include <iostream>  
using namespace std;  
void printArray(int arr[5]);  
int main()  
{  
        int arr1[5] = { 1, 2, 3, 4, 5 };    
        int arr2[5] = { 6, 7, 8, 9, 10 };    
        printArray(arr1); 
        printArray(arr2);  
}  
void printArray(int arr[5])  
{  
    cout << "Array elements:"<< endl;  
    for (int i = 0; i < 5; i++)  
    {  
                   cout<<arr[i]<<"\n";    
    }  
}

Output

Array elements:                                                              
1                                                                                    
2                                                                                    
3                                                                                    
4                                                                                    
5                                                                                    
Array elements:                                                              
6                                                                                     
7                                                                                    
8                                                                                    
9                                                                                    
10

 

Read more, Multidimensional arrays in C++

Share this post

Leave a Reply

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