Example program passing array as function argument in C C++

Coding in C

#include<stdio.h>
void display(int[],int);
int main()
{
    int a[5],i=0;
    printf("Enter values: ");
    for(i=0;i<5;i++)
    scanf("%d",&a[i]);
    display(a,5);
    return 0;
}
void display(int a[], int n)
{
    int i=0,sum=0;
    for(i=0;i<n;i++)
    {
        printf("Element = %d\n",a[i]);
        sum=sum+a[i];
    }
    printf("Sum = %d",sum);
}

Coding in C++

#include<iostream>
using namespace std;
void display(int[],int);
int main()
{
    int a[5],i=0;
    cout<<"Enter values: ";
    for(i=0;i<5;i++)
    cin>>a[i];
    display(a,5);
    return 0;
}
void display(int a[], int n)
{
    int i=0,sum=0;
    for(i=0;i<n;i++)
    {
        cout<<"Element = "<<a[i]<<endl;
        sum=sum+a[i];
    }
    cout<<"Sum = "<<sum;
}

Output

Example program for passing array as function argument in C
Share it to:

Published by

admin

I am a computer teacher, programmer and web developer