For loop help!

I have to write just a simple for loop that counts down from 99 bottles of beer on the wall. I can complete the for loop easily when counting up, but when I try to do it counting down using the i--, I keep getting infinite loops going in the negative direction. Please help. I know its simple, but I can't seem to figure it out.

1
2
3
4
5
6
7
8
  int main()
{
    int number = 99;
    for(int i = 0; i <= number; i++)
        cout << i << " numbers of beer on the wall" << endl;

    cin.get ();
}
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
{
	int number = 0; // your ending point
	for (int i = 99; i >= number; i--) // initialize 'i' as your starting point
		cout << i << " numbers of beer on the wall" << endl;

	cin.get();
}
Also, let's take this WRONG example
1
2
3
4
5
6
7
8
9
int main()
{
    int number = 99;
    for(int i = 0; i <= number; i--) // changed to i--.  Look familiar?
        cout << i << " numbers of beer on the wall" << endl;

    cin.get ();
return(0);
}


The reason you get an infinite loop is because the condition is never made false. 'i' begins at zero, and 1 is subtracted from it every time the loop runs. 'i' will never be greater than 99, as you are counting backwards.

Therefore, you must initialize your 'i' value as the starting point, and end it with the other variable (in this case, 'number')

**YOU MUST UNDERSTAND THE FOR LOOP***

For this example, we will look at your original code, counting in ascending order to 99.
1
2
3
4
5
6
7
8
  int main()
{
    int number = 99;
    for(int i = 0; i <= number; i++)
        cout << i << " numbers of beer on the wall" << endl;

    cin.get ();
}

Here is how it works:

for (starting value; test expression; change in value)

You first define a variable as the starting value.

Then, it checks variable against the test expression. If it is true (I.E. the conditions are satisfied), the loop continues running. In your case, if 'i' is greater than 99, it will be false and the loop will stop.

Finally, the variable must be modified in a way that it ultimately makes the condition false. In my example, this action that modifies the starting value is called the change in value.

It is very important for you to understand the for loop. You will use it a lot.
Last edited on
awesome man thanks! I could have sworn I tried that combination, but I kept getting an infinite negative loop. I guess I don't really understand the walk through of it though because if you start at i = 99 and number = 0 and then you say i is greater than or equal to number which obviously 99 is greater than 0, but why wouldn't it continue to be infinite? I get that i value gets subtracted by 1, but I guess the logic of it is escaping me.
I was editing my last reply in order to explain what you just asked me to do =) Let me know if this clarifies it for you, and if so, please mark the thread as solved.
Topic archived. No new replies allowed.