Can someone please briefly explain why the output is 55
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main()
{
int sum = 0, val = 1;
// keep executing the while as long as val is less than or equal to 10
while (val <= 10) {
sum += val; // assigns sum + val to sum
++val; // add 1 to val
}
cout << "Sum of 1 to 10 inclusive is " << sum << endl;
return 0;
}
You can figure out this yourself :+) Just put a cout that prints the value of sum after line 8.
Seen as you know how many times you want to loop, you can use a for loop:
1 2 3 4 5 6 7
constunsignedint Limit = 10;
unsignedint sum = 0;
for (unsignedint val = 1; val < Limit + 1; ++val) {
sum += val;
std::cout << "Sum is " << sum << "\n";
}