Level 0, lesson 20

# 0.20 FOR-NEXT constructs

4tH does also have FOR-NEXT constructs. The number of iterations is known in this construct. E.g. let's print the numbers from 1 to 10:

         11 1 do i . cr loop

The first number presents the limit. When the limit is reached or exceeded the loop terminates. The second number presents the initial value of the index. That's where it starts of. So remember, this loop iterates at least once! You can use '?DO' instead of 'DO'. That will not enter the loop if the limit and the index are the same to begin with:

         0 0 ?do i . cr loop

'I' represents the index. It is not a variable or a constant, it is a predefined word, which puts the index on the stack, so '.' can get it from the stack and print it.

But what if I want to increase the index by two? Or want to count downwards? Is that possible. Sure. There is another construct to do just that. Okay, let's take the first question:

         11 1 do i . cr 2 +loop

This one will produce exactly what you asked for. An increment by two. This one will produce all negative numbers from -1 to -10:

         -11 -1 do i . cr -1 +loop

Note that the step is not a literal expression. You can change the step if you want to, e.g.:

         32767 1 do i . i +loop

This will print: 1, 2, 4, 8, all up to 16384. Pretty flexible, I guess. You can break out of a loop by using 'LEAVE'. Note that 'LEAVE' only sets the index to the value of the limit: it doesn't branch or anything. Make sure that there is no code left between 'LEAVE' and 'LOOP' that you don't want to execute. So this is okay:

         10 0 do i dup 5 = if drop leave else . cr then loop

And this is not:

         10 0 do i dup 5 = if drop leave then . cr loop

Since it will still get past the '.' before leaving. In this case you will catch the error quickly, because the stack is empty.