Sunday, 12 January 2014

Adding elements in array in c++ using functions

Definition
An array is basically a series of objects of same type. Each object in an array is known as an array element. Our motive here is to find the sum of elements stored in an array entered by the user. An array is declared as: 
int arr[10];
where arr[ ] is the array and arr[1], arr[2], arr[3] so on.. are the array elements. Values could be assigned to these array elements as:
arr[1]=10;
arr[2]=7;
arr[3]=13;
Sample Program
:
#include <iostream>

using namespace std;

int main()
{
    int a[10],n,i;
    int sum(int [],int n );
    cout << "Enter size of array=" << endl;
    cin>>n;
    cout<<"Enter array elements=";
    for(i=0;i<n;i++)
    {
    cin>>a[i];
    }
    cout<<"Sum is="<<sum(a,n);
}
    int sum(int a[],int n)
    {
        int s=0,i;
        for(i=0;i<n;i++)
        {
        s=s+a[i];
        }

        return s;
    }


This entry was posted in :

0 comments:

Post a Comment