19.04.2017 Views

Learn to Program with Small Basic

Create successful ePaper yourself

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

Introducing the For Loop<br />

As you start writing longer programs, you’ll need <strong>to</strong> repeat some statements.<br />

For example, let’s make the turtle draw a square: enter the code<br />

shown in Listing 5-6.<br />

1 ' Square1.sb<br />

2 Turtle.Move(60) ' Moves 60 pixels<br />

3 Turtle.TurnRight() ' Turns right 90 degrees<br />

4 Turtle.Move(60) ' Moves 60 pixels<br />

5 Turtle.TurnRight() ' Turns right 90 degrees<br />

6 Turtle.Move(60) ' Moves 60 pixels<br />

7 Turtle.TurnRight() ' Turns right 90 degrees<br />

8 Turtle.Move(60) ' Moves 60 pixels<br />

9 Turtle.TurnRight() ' Turns right 90 degrees<br />

Listing 5-6: Making the turtle draw a square<br />

The turtle starts facing upward. This code tells the turtle <strong>to</strong> move<br />

60 pixels up <strong>to</strong> draw one side of the square, turn 90 degrees <strong>to</strong> the right,<br />

move 60 pixels <strong>to</strong> draw another side, turn 90 degrees <strong>to</strong> face downward,<br />

move 60 pixels <strong>to</strong> draw a third side, turn 90 degrees <strong>to</strong> face left, and move<br />

60 pixels <strong>to</strong> complete the square. Finally, the turtle turns 90 degrees one<br />

last time so it’s facing upward like it was at the beginning. Check out the<br />

result in Figure 5-9. Does your screen look the same?<br />

20<br />

Start<br />

Turtle.Move(60)<br />

Turtle.TurnRight()<br />

Turtle.Move(60)<br />

Turtle.TurnRight()<br />

Turtle.Move(60)<br />

Turtle.TurnRight()<br />

Turtle.Move(60)<br />

Turtle.TurnRight()<br />

Figure 5-9: Drawing a square using move and turn commands<br />

You repeated the Move(60) and TurnRight() methods four times. The computer<br />

doesn’t mind repeating these tasks, but it’s boring for you <strong>to</strong> type all<br />

that code. Wouldn’t it be great if you could make the turtle draw this square<br />

using an easier approach?<br />

Well, you can! You can make the turtle draw the same square as in<br />

Listing 5-6, just by using a few lines of code. Use a For loop, like the one<br />

in Listing 5-7.<br />

1 ' Square2.sb<br />

2 For I = 1 To 4 ' Repeats 4 times<br />

3 Turtle.Move(60) ' Draws one side<br />

4 Turtle.TurnRight() ' Turns right 90 degrees<br />

5 EndFor<br />

Listing 5-7: Making the turtle draw a square using a For loop<br />

62 Chapter 5

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

Saved successfully!

Ooh no, something went wrong!