Program : Compute the sum of all elements in a 1-D array in C++
Solution :
#include <iostream> using namespace std; int main() { const int size = 5; // Change the size to fit your array int arr[size],i,sum=0; // Input the array elements cout << "Enter " << size << " elements of an array:\n"; for (i = 0; i < size; i++) { cin >> arr[i]; } // Compute the sum of array elements for (i = 0; i < size; i++) { sum += arr[i]; } // Output the sum cout << "Sum of array elements: " << sum; return 0; }
Output :
Enter 5 elements of an array: 3 7 2 9 5 Sum of array elements: 26
Dry Run :
i | i<size | arr[i] | sum=sum+arr[i] | i++ |
0 | True | arr[0]=3 | = 0 + 3 => 3 | 1 |
1 | True | arr[1]=7 | = 3 + 7 => 10 | 2 |
2 | True | arr[2]=2 | = 10 + 2 => 12 | 3 |
3 | True | arr[3]=9 | = 12 + 9 => 21 | 4 |
4 | True | arr[4]=5 | = 21 + 5 => 26 | 5 |
5 | False | —————- | ————– | —————— |
So, the final value of “sum” is 26 and it will print 26.
Want to practice more problems involving Array 1-D ? Click here.