Wednesday, 5 August 2015

C plus plus Program to find sum of elements in a given array

Leave a Comment
Questions:

C plus plus Program to find sum of elements in a given array

Code:


/* C plus plus Program to find sum of elements in a given array  */
#include<iostream>
using namespace std;
#define MAX_SIZE 100

// C plus plus program to return sum of elements in an array of size n
int sum(int arr[], int n)
{
    int sum = 0; // initialize sum
    int i;

    // Iterate through all elements and add them to sum
    for (i = 0; i < n; i++)
       sum +=  arr[i];

    return sum;
}

int main()
{
    int arr[MAX_SIZE];
    int n, i;
    cout<<"Eneter the number of elements in array\n";
    cin>>n;
    cout<<"Enter Elements \n";
    for (i = 0; i < n; i++)
    cin>>arr[i];
    cout<<"Sum of the elements is "<<sum(arr, n);
    return 0;
}




Output


If You Enjoyed This, Take 5 Seconds To Share It