Calculate the sum of elements in an array in C++

Program to calculate the sum of elements in an array in C++

 

Here, in this page we will discuss a C++ Program to find the sum of the elements of an given input array.

Example : Arr[5] : {10, 20, 30, 40, 50}

Sum of the given array elements are : 10+20+30+40+50 = 150

C code

Algorithm :

 

  • Take the size of the array from the user and store it in variable say N.
  • Take N elements of an array from the user and store them in a an array say Arr[].
  • Declare a variable say sum that store the elements sum in it and initialize sum = 0.
  • Now, Run a loop from 0 to N-1 and add the corresponding ith value in the variable sum.
  • Print the sum on the output screen.
sum of elements of aray in c++

C++ code based on above algorithm

#include <iostream>
using namespace std;
int main(){

int n;
cin>>n;

int a[n], sum = 0;

for (int i = 0 ; i < n; i++)
cin>>a[i];

for(int i = 0; i < n; i++)
sum += a[i];

cout<<sum ;
}
Input :



10 20 30 40 50

Output :

150