Misunderstanding a simple for loop

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>
using namespace std;

int main ()
{
  for (int n=10; n>0; n--) {
    cout << n << ", ";
  }
starts at 10 works its way down to 1
I know that, but from what I see, by the time the cout command is called, the for loop should have already decremented it from 10 to 9.

Yet it doesn't appear to have done so and just outputs 10 first.
closed account (48T7M4Gy)
The first run through the loop starts with ten.
http://www.cplusplus.com/doc/tutorial/control/
It works in the following way:

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).
This is the for loop expressed as while:
1
2
3
4
5
6
7
8
9
10
  #include <iostream>
using namespace std;

int main ()
{
  int n=10;
  while (n>0) {
    cout << n << ", ";
    n--; // Note
  }
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.

Thanks guys.
Topic archived. No new replies allowed.