Don’t worry, unlock all articles / blogs on PrepInsta by just simply logging in on our website
C++ program to find sum of elements in an array
November 6, 2021
Finding sum of elements in an array in C++
In this article, we will learn to program to find the sum of elements in an array in C++. For this, we will iterate each element through a for loop and will add each element in the previous sum repeatedly on every iteration. Steps and algorithm for the same is given in detailed below.
Steps to find sum of element in an array in C++
Following steps are followed while finding the sum of element in an array:-
Initialize the required variables.
Accept the inputs from user.
Iterate each element of the array using a for loop.
Add every element that is iterated in any other variable for ex sum.
Print that variable.
Algorithm to find sum of element in an array
Start
Sum=0
For i= 0 to n-1
Sum+=arr[i]
Exit
C++ programming code to find sum of element in an array
#include <iostream>
using namespace std;
int main()
{
int arr[100],i,size,sum=0;
cout<<"Enter the number of elements: ";
cin>>size;//Accepting array size
cout<<"Enter the value of elements: "<<endl;
for(i=0;i<n;i++)
{
cin>>arr[i]; //Accepting values
}
for(i=0;i<n;i++)
{
sum=sum+arr[i];//Calculating sum
}
cout<<"Sum of elements in an array is: "<<sum;
return 0;
}
Output:
Enter the number of elements: 5
Enter the value of elements:
7
10
3
12
5
Sum of elements in an array is: 37
Inside the loop there should be size variable instead of n.
Hey there,
Thanks for answering, Kindly join our Discord server for all your subjected related queries.