Simple Array Sum Program in C++
ADVERTISEMENTS
Simple array sum program in c++.
In this article, you will learn how to make a simple array sum program in c++.
Example
array = [5, 6, 7]
sum = 5 + 6 + 7
It will return sum = 18
You should have knowledge of the following topics in c++ programming to understand these programs:
- C++
main()
function - C++
while
loop - C++
for
loop
Source Code
// Simple Array Sum Program in C++
#include <iostream>
using namespace std;
int main() {
int s;
cout << "Enter size of the array:\n";
cin >> s;
int arr[s], i=0, sum=0;
cout << "\nEnter the elements of the array:\n";
while (i<s) {
cin >> arr[i];
sum += arr[i];
i++;
}
cout << "\nSum = " << sum;
return 0;
}
Output
Enter size of the array:
8
Enter the elements of the array:
1 3 5 7 8 9 23 56
Sum = 112
Explanation
In this given program, we have taken the size of the array 6
from the console input and then entered the 6 elements one by one 1, 3, 5, 7, 8, 9, 23, 56
. Then we make iteration over on these elements and every element is added with the sum variable.
Then sum variable return the 112
output of the final program.
Simple Array Sum Program in C++ using For loop
// Simple Array Sum Program in C++ using For loop
#include <iostream>
using namespace std;
int main() {
int s;
cout << "Enter size of the array:\n";
cin >> s;
int arr[s], sum=0;
cout << "\nEnter the elements of the array:\n";
for (int i=0; i<s; i++) {
cin >> arr[i];
sum += arr[i];
}
cout << "\nSum = " << sum;
return 0;
}