Navigation:  Tutorials > Beginners Guide to Smalltalk > Control Flow >

Iterating Through a Range of Values

Previous pageReturn to chapter overviewNext page

Sometimes you'll want to loop a number of times and know where you are in the sequence as you do so. For example, let's say that we want to print a list of the square numbers from 1 to 12.

1 to: 12 do: [:n |

       Transcript show: n squared displayString; cr ].


After evaluating this code in the System Transcript window to see the results. You can send text strings to this window using a #show: message sent to the global variable, Transcript. More importantly, take a look at the #to:do: message and the format of the block it takes as its second parameter. The receiver is an integer which represents the starting value and the first parameter is taking to be the ending value. The block is then executed for this range with each value in turn being passed as a parameter (n) to the block. Yes, that's right; blocks can have parameters too.

If a block is to expect one or more parameters then they must be declared immediately after the opening bracket. Each parameter is preceded by a colon and separated by a space. The parameter list is terminated by a vertical bar character.

The #to:do: message in the previous example loops through a range of integer values stepping one at a time. If you wish to increase the size of the step then the message #to:by:do: exists for this purpose:

10 to: 120 by: 10 do: [:eachRadius | simon radius: eachRadius ].

40 to: 220 by: 20 do: [:eachAngle | simon rotation: eachAngle ]


In a later chapter you will see how you can iterate over more complicated collections of objects, not just integer ranges.