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
int sum = 0;
int num = 1;
while (sum <= 10000)
sum = sum + (num ++);
cout << sum << endl;
cout << num << endl;
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
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.