06.06.2013 Views

Computer Programming with GNU Smalltalk - Free

Computer Programming with GNU Smalltalk - Free

Computer Programming with GNU Smalltalk - Free

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

50 <strong>Computer</strong> <strong>Programming</strong> <strong>with</strong> <strong>GNU</strong> <strong>Smalltalk</strong><br />

This structure starts from number aNumber and evaluates the aBlock object until it reaches<br />

anotherNumber. It increases one at every loop. aBlock object also includes a block argument so that<br />

programmer can use the current index in expressions of aBlock.<br />

We mentioned that whileTrue: message is usually used <strong>with</strong> indefinite cases. to:do: on the<br />

contrary, is used when it is known how many loops we needed. That's why it is sometimes called<br />

definite loop.<br />

For experienced programmers:<br />

Being a definite loop, you might guess that this message is used in <strong>Smalltalk</strong> instead of for loop of C<br />

based languages.<br />

Now let's look at this structure via an example:<br />

"5_lines.st"<br />

"A program which prints 5 lines to demonstrate the usage of to:do: message."<br />

1 to: 5 do: [:x |<br />

Transcript show: 'This is the ', x printString, '. line.'; cr.<br />

]<br />

This is the 1. line.<br />

This is the 2. line.<br />

This is the 3. line.<br />

This is the 4. line.<br />

This is the 5. line.<br />

This program prints five lines to the output each indicating their own index. Note that we used a block<br />

argument, x, for getting the index of each loop. If we didn't write an argument for block object then we<br />

would get an error.<br />

to:by:do:<br />

Sometimes we might not want to increase the index of to:do: message one by one. There is an<br />

alternative message called to:by:do: for this purpose. Its general structure is like this:<br />

aNumber to: anotherNumber by: step do: aBlock<br />

It allows us to reach the number anotherNumber in steps of the number defined by step. For<br />

example, write the same example above, this time by using this alternative message to increase the<br />

index two by two. Also count until ten, this time, so that the loop does not end very quickly:<br />

"tobydo.st"<br />

"A program to demonstrate the usage of to:by:do: message."<br />

1 to: 10 by: 2 do: [:x |<br />

Transcript show: 'This is the ', x printString, '. line.'; cr.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!