### Problem solving Loop Practice Problem from Jumping into C++

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
 ``123456789101112131415`` ``````#include using namespace 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.
Use sentinel values and a while loop and make total 0. Then add the input to it.

Pseudo-Code:
 ``123`` ``````total=0; while (user_input!=0) {add the input to the total}``````
Last edited on
Let me teach you three loops.

First, the for loop.
 ``1234`` ``````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.

 ``123456`` ``````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.
 ``12345`` ``````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:
 ``12345678910111213141516171819`` ``````#include using namespace 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:

 ``12345678910111213141516171819`` ``````#include using namespace 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 :).
Last edited on
Topic archived. No new replies allowed.