Home >Backend Development >C++ >C/C++ program to find the sum of elements in a given array

C/C++ program to find the sum of elements in a given array

王林
王林forward
2023-08-28 13:46:041382browse

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

Explanation

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

Example

#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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:ups and downs numbersNext article:ups and downs numbers