To get a sum of all elements from an array of integers, we will use simple incremental addition with a help of a for loop.
Starting point for loop will be zero, ending point will be number of elements.
While jumping from one element to another, we will incrementaly add previous elements until we reach top level, in this case number 5.
We must not skip any of elements, thus increment must x = x + 1.
Run this code:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {23, 34, 56, 5000, 2};
int total = 0;
for (int x = 0; x < 5; x = x + 1) {
total = total + numbers[x];
cout << "Result of addition at this pass: " << x << " -> " << total << endl;
}
return 0;
}
Result:
Result of addition at this pass: 0 -> 23
Result of addition at this pass: 1 -> 57
Result of addition at this pass: 2 -> 113
Result of addition at this pass: 3 -> 5113
Result of addition at this pass: 4 -> 5115
Process returned 0 (0x0) execution time : 0.065 s
Press any key to continue.
No comments:
Post a Comment