I am currently going through "Jumping into C++" by Alex Allain, and I am absolutely stuck at the Chapter 5 Practice Problem #3 which entitles "Write a program that computes a running sum of inputs from the user, terminating when the user gives an input of 0.". For the life of me I can't seem to comprehend or understand how to go about this at all... I'm having a really hard time wrapping my head around loops or knowing which loop to use for what purpose.
What I have so far is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main()
{
int num1, num2, total;
total = 0;
cout << "Please enter a number: ";
cin >> num1;
cout << "please enter a second number: ";
cin >> num2;
}
Thank you so much for helping me learn and help make me understand loops better.
for(unsigned i=0 /*declaration*/; i<10 /*condition*/; i++/*iteration*/)
{
//this body will be repeated 10 times, with 'i' incrementing post-execution
}
Next, the while loop.
1 2 3 4 5 6
unsigned i=0;
while(i < 10 /*condition*/)
{
++i;
//this body will be iterated again if the condition is met with true
}
Next, the do-while loop.
1 2 3 4 5
int i=0;
do //body will be executed at least once
{
++i;
}while(i<10); //re-do if the condition is met
well After trying to figure out from your helpful code, I came up with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main()
{
int input, total;
total = 0;
input = 1;
while(input != 0)
{
cout << "Please enter a number: ";
cin >> input;
total = total + input;
cout << "Total: "<< total << endl;
}
return 0;
I didn't know initializing input to 1 would make my while work... I had it at 0 before and nothing showed up until I changed it to 1. Now that I figured it out, it seems ever so simple... Thanks guys for your help :).
::Edit::
I just realized that doing a do-while loop was more practical in this case because it needs to user's input before the loop begins. I ended up doing it his way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
int main()
{
int input, total;
total = 0;
do
{
cout << "Please enter a number: ";
cin >> input;
total = total + input;
cout << "Total: "<< total << endl;
}while(input != 0);
return 0;
}
I'm slowly starting to get the hang of these loops :).