More Loops

Skipping index

You can skip an index using the word +LOOP

			: skip5 25 0 do  i . 5 +LOOP ; 
			skip5
		
should display
0 5 10 15 20 ok

Note that 25 is not printed, even though it equals to the end index.
However, if the skip is negative, i.e., counting down. You get the end index.

			: skip5down 0 25 do i . -5 +loop ;
			skip5down
		
should display
25 20 15 10 5 0	 ok

Stopping a DO...LOOP

To stop a 
DO
loop use the words
LEAVE
and
UNLOOP
:
  1. LEAVE
    simply leaves the loop, and executing continues after LOOP
  2. The pair
    UNLOOP EXIT
    must be used if you want to exit the word completely.

Some examples:

			: short 
				100 0 do  
					i dup . 2 = if LEAVE then 
				loop 
				"Hello!" . 
			;
	
			short
		
will display
0 1 2 Hello! ok

Another example:

			: never-ever 
				100 0 do 
					i dup . 
					2 = if UNLOOP exit then 
				loop 
				"I will never be printed!" . ;
				
			never-ever
		
will only print
0 1 2 ok

Be sure you try out these examples and thoroughly understand them before moving on!

Quiz

Question 1

What do you think would happen if we changed the 100 0 in 
SHORT
to 100 2 ? Try to guess the answer then experiment with the Smojo Terminal.



Question 2

What do you think would happen if we changed the LOOP in 
NEVER-EVER
to 5 +LOOP ? Guess the answer then check with the Terminal.



Next: Other Looping Constructs