Home > Article > Backend Development > C/C++ program to find the sum of elements in a given array
Sum of all array elements means adding all array elements. Suppose we have 5 array elements and we want to find their sum.
arr[0]=1 arr[1]=2 arr[2]=3 arr[3]=4 arr[4]=5
The sum of all the above elements is
arr[0]+arr[1]+arr[2]+arr[3]+ arr[4]=1+2+3+4+5=15
Input:1,2,3,4,5 Output:15
Use a For loop to iterate through each index element and Add them up
arr[0]+arr[1]+arr[2]+arr[3]+ arr[4]=1+2+3+4+5=15
#include <iostream> using namespace std; int main() { int i,n,sum=0; int arr[]={1,2,3,4,5}; n=5; for(i=0;i<n;i++) { sum+=arr[i]; } cout<<sum; return 0; }
The above is the detailed content of C/C++ program to find the sum of elements in a given array. For more information, please follow other related articles on the PHP Chinese website!