Home > Backend Development > C++ > body text

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

王林
Release: 2023-08-28 13:46:04
forward
1304 people have browsed it

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
Copy after login

The sum of all the above elements is

arr[0]+arr[1]+arr[2]+arr[3]+ arr[4]=1+2+3+4+5=15
Copy after login
Copy after login

Input:1,2,3,4,5
Output:15
Copy after login

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
Copy after login
Copy after login

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;
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!