# Help on loops

• 12-02-2005
GAMEPROJO3
Help on loops
Im trying to get this program to add the numbers to eachother after each gets executed, and 0 is suppose to terminate the program. Am I using the wrong loop? Anyone give me some tips please?

Code:

``` #include <iostream> using namespace std; int main() {     cout << " Please enter a number";     int num;     cin >> num;     cin.get();     for (int i = num; i != 0; i++)         {             cout << " Number is now : " << i << endl;             i += i;             cin >> i;             cin.get();             };             cout << "Terminating Program now";             cin.get();             return 0; }```
• 12-02-2005
7stud
Code:

`for (int i = num; i != 0; i++)`
That says starting at num:

int i = num

count upwards:

i++

until i does not equal 0:

i !=0

If you enter 3 as the number, how are you ever going to reach 0 counting upwards by 1?

This:

i += i;

is the same as multiplying 'i' by 2. Why are you multiplying your loop counter by 2? Then you read a number into your loop counter:

cin >> i;

??? Why are you abusing your loop counter like that? You aren't treating it as a loop counter, so why even have a loop counter?

You need to use a while loop. A while loop will continue executing forever until the while condition is false. So, you need to decide what condition should end the loop.

Then you need to read in a number, add it to a total, and let the loop do its thing. When the loop ends display the total.
• 12-02-2005
GAMEPROJO3
Wont i != 0 terminate the program when the user enters a 0? What would I need to do to make it add instead of multiply? I basically want it to keep adding the numbers the user enters. Its been a while since ive programmed in c++ and forgot alot of stuff about it :(
• 12-02-2005
7stud
Quote:

Wont i != 0 terminate the program when the user enters a 0?
I guess that's one way of looking at it. A loop counter should do one thing: count loops. It can't count loops if you are reading values into it. And, if you aren't going to use it to count loops, why have a loop counter in the first place?