While loop issue...

I'm doing a bit of homework for my c++ class and this problem came up: use a while loop to sum the integers starting at 1 until the sum is no greater than 10,000. Also output the most recent added number.

Ok. Easy, this is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()

{	
	int sum = 0;
	int num = 1;

	while (sum <= 10000)
	{
		sum = sum + (num ++);
		cout << sum << endl;
	}
	cout << num << endl;

	return 0;
}


Simple enough; works like a charm. However, when it runs the loop it stops at 10,011...
Before I was able to correct it by subtracting the extra from the <= bit (the flag?)
This time it didn't work. I was wondering why it does this? if the program says don't go over 10k then it should just not add the number that would push it over.


NOTE: I also tried this with just a less than symbol and it also gave me 10,011
closed account (3CXz8vqX)
1
2
3
4
5
for (int sum = 0; sum <=10000; sum = sum + num)
	{
	    num++;
	    cout << sum << endl;
	}


Works better. >.>;

Edit. Okay... the for loop may not be what you're after admittedly. It would help if I understood the question.


...try this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()

{
	int sum = 0;
	int num = 1;

	while (sum <= 10000)
	{
        cout << sum << endl;
		sum = sum + (num ++);
	}
	cout << num << endl;

	return 0;
}

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
	int sum = 0, n = 0;

	while ( sum + n + 1 <= 10000 ) sum += ++n;

	std::cout << "sum = " << sum << ", the last item = " << n << std::endl;

	return 0;
}
The program says that if 'sum' is still below 10001, then add whatever value the 'num' contains. That is different from keeping the sum below 10000. Your conditional has to take into consideration what shall happen.

You dont show the last added number. You have changed 'num' after the addition.

< and <= do differ only when 'sum == 10000'. It doesn't in your program. Ever.
Last edited on
closed account (3CXz8vqX)
Rofl, apparently I 'bodged' my solution =D
Thanks for the help guys!
Topic archived. No new replies allowed.