array to function in C++ .

In this session i have discussed array to function in C++ .


We can pass the array in function as parameter . You need to declare the array in function as argument .


Example : Write a program that demonstrate the how to pass the array in function .

    #include<iostream>
    using namespace std;  
    void display(int arr[],int size)
    {
        int i;
        for(i=0;i<size;i++)
        {
            cout<<arr[i];
            cout<<" ";
        }
    }
    int main()
    {
        int arr[]={10,20,30};
        display(arr,3);
        return 0;
    }
    OUTPUT : 10 20 30
    


Example : Write a program in which pass the array as function argument that find the max value .

    #include<iostream>
    using namespace std; 
    void MaxFunction(int arr[],int size)
    {
        int i;
        int max;
        max=0;
        for(i=0;i<size;i++)
        {
            if(max<arr[i])
            {
                max=arr[i];
            }
        }
        cout<<"Max : "<<max;
    }
    int main()
    {
        int arr[]={10,20,30};
        MaxFunction(arr,3);
        return 0;
    }

    
    OUTPUT : Max : 30
    


Example : Write a program in which pass the array as function argument . Function sort the array in descending order .

    #include<iostream>
    using namespace std; 
    int main()
    {
            int temp;
            int i,j;
            int arr[]  = { 10, 30, 60, 40, 50 };
            temp = 0;
            for(i=0;i<5;i++)
            {
                for (j = i+1; j <5;j++ )
                    if (arr[i] < arr[j])
                    {
                        temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                    }
           
            }
            for(i=0;i<5;i++)
            {

                cout<<arr[i];
                cout<<" ";
            }
            return 0;
    }
    
    OUTPUT : 60 50 40 30 10
    

Welcome to AndroidATPoint.

back image                     next image