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>
usingnamespace 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.
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!
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.
#include <iostream>
usingnamespace 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.