While loop problem

The problem is: Write a code segment using a While loop that sums the integers, counting up from 1, and stops when the sum is greater than 10,000, printing out the integer that was most recently added to the sum.

This is the code I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main ()
{

int s = 0;
int i;

for (int i = 1; i <= 10000; i++)
s= s + i;

cout << " s = " << s << endl;
}


It does everything I want except include the last entered value of i. Can't I just add a cout << "last integer entered is: " << i << endl? I tried that, but I keep getting an error. Any input would be appreciated.

Thanks!

EDIT: I see that my i <=10000 is not going to work there because the sum is much greater than 10000. I'll fix that once I figure it out.
Last edited on
Well the first thing that comes to mind is that your assignment says "using a while loop", while you are using a for loop.

You will need to rewrite your code with a while loop.
1
2
3
4
5
do{
//enter commands you want to be repeated
}
while(/*enter condition*/);
//the commands between {} will be repeated as long as the condition is true 


Also you can out the while(/*condition*/); before do{/*enter code*/} if you want your condition to be evaluated BEFORE the loop is executed.

I hope this helps
Last edited on
Ugh. He did not teach us how to use a while loop for the sum. I'll have to figure that out. He gave us an example with just the for loop. Thank you for posting that though!
Last edited on
Okay this is the new code. But yet again, I'm just really confused with the whole outputting the last integer bit of the problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main ()
{
int num = 1;
int sum = 0;

while (num <= 140)

sum = sum + num++;
cout << sum << endl;

return 0;
}


I was getting confused with all the i's and s's so sorry for the whole code change.
Last edited on
Try as borekiller suggested, a do .. while() loop

1
2
3
4
do
{
    sum = sum + num++;
} while (num <= 140);


The benefits of a do .. while() to a while() loop is that it will execute at least once, even if the condition is fulfilled already, while a while() loop won't.
Aha!

This is what I have now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main ()
{
int num = 1;
int sum = 0;

do
{
	sum = sum + num++;
} 
	while (num <= 140);

	cout << "The last integer added to the sum was: " << num << endl;
	cout << "The total sum (without the last integer is): " << sum << endl;
}


Thank you both for the help. We did not learn the do thing yet, but it makes things a lot simpler.
Last edited on
you can also do a if flow control statement.

Put this in the function to make sure that right when the integer reaches > 10000 it will use the break keyword to get out of the function.
Topic archived. No new replies allowed.