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.