Again, a stupidly simple problem that has be vexed.
In the below code, n is set to 10, n is then checked to see if it is greater than zero, it is, so n is then evaluated, decremented, causing it to be set to 9.
So cout << n << "."; should output 9 to the monitor, correct? Since n was decremented, and then when called by the cout command, it is evaluated again and will output 9.
Yet whenever I run this code, it outputs the value of 10 first, then 9, then 8, etc. How does it output the value of 10 if the first time the for loop is run, it decrements n to 9 before the cout command is first called?
1 2 3 4 5 6 7 8
#include <iostream>
usingnamespace std;
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
1.initialization is executed. Generally, this declares a counter variable, and sets it to some initial value. This is executed a single time, at the beginning of the loop.
2.condition is checked. If it is true, the loop continues; otherwise, the loop ends, and statement is skipped, going directly to step 5.
3.statement is executed. As usual, it can be either a single statement or a block enclosed in curly braces { }.
4.increase is executed, and the loop gets back to step 2.
5.the loop ends: execution continues by the next statement after it.
Note that the increment/decrement is executed at the bottom of the loop (line 8).
Oh okay, I missed that when following tutorials. I got confused and assumed it executed from left to right, so it would always decrement, then do the following statement, not jump from the for part, to the statement, then back to the for loop's increase.