# Raw beginner's first loop: Why does it print 0 to 9 rather than 1 to 10?

Twine 2. Sugarcube 2.34.1

<<for _i to 0; _i lt 10; _i = _i+1>>
_i
`<</for>>`

I set the counter to 0, then change it to 1, and then print it.

But it prints 0 rather than 1.

On the final pass, the counter equals 9 when tested, then it is incremented to 10 and printed, and yet the last number printed is 9. Again, I don’t see why that is.

I’m wondering why this is. Does the code not execute in the order humans read it?

The post expression is executed after the 3-part loop iteration, not before.

``````<<for INIT ; CONDITIONAL ; POST>>
LOOP CONTENTS
<</for>>
``````

In order:

1. `INIT` is executed once. Generally, to initialize any loop variables.
2. `CONDITIONAL` is checked. If it yields truthy, then go to step 3, else stop the loop.
3. `LOOP CONTENTS` are executed.
4. `POST` is executed.
5. Repeat step 2.

SEE: `<<for>>` macro for additional details.

1 Like

Right, this is based on some programming language traditions that were more about what was convenient for the computer rather than what was convenient to the programmer.

So it starts with the first statement (initialize `_i` to 0).

Then each time through the loop it checks the second statement (`_i lt 10`) to see if it should do the loop thing (if true) or exit the loop (if false).

Then at the end of the loop it does the third thing (`_i = _i + 1`) and then goes back to the top to check the condition again.

So if `_i` is 9, then you print it, you increment it to 10, and then it goes back to the top and checks. Now it’s no longer less than 10, so it skips the loop body and doesn’t print 10.

Hope that helps…

1 Like

Thanks. That clears that up for me.

Thanks, Josh.

I could make my loop print 1 thru 10 by tinkering with it, but I wanted to understand the why of it. You explained it clearly.