Please help c++ beginner

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>
using namespace 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;	
}
The sum from 1 to 10 is 55.

Trace the code using pen and paper. Make a note of how each variable changes with each iteration of the loop.

By the way, there is a simple formula for calculating the sum from 1 to n: n(n+1)/2
Last edited on
Hi,

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
const  unsigned int Limit = 10;
unsigned int sum = 0;

for (unsigned int val = 1; val < Limit + 1; ++val) {
   sum += val;
   std::cout << "Sum is " << sum << "\n";
}


Hope this helps :+)
Topic archived. No new replies allowed.