19.04.2017 Views

Learn to Program with Small Basic

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

TRY IT OUT 13-5<br />

What does the following program do? Run the program <strong>to</strong> check your answer.<br />

For N = 1 To 200<br />

GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor()<br />

x2 = Math.GetRandomNumber(300)<br />

y2 = Math.GetRandomNumber(300)<br />

GraphicsWindow.DrawLine(0, 0, x2, y2)<br />

EndFor<br />

Changing the Step Size<br />

The previous section showed you the syntax of the For loop that au<strong>to</strong>matically<br />

increases the loop counter by one after each iteration. But For loops<br />

have a general form that lets you control the Step size of the loop’s control<br />

variable <strong>to</strong> increase it or decrease it by however much you want. Here’s the<br />

general form of the For loop:<br />

For N = A To B Step C<br />

Statement(s)<br />

EndFor<br />

It works like the simplified loop you saw earlier. But instead of incrementing<br />

the loop counter N by one, you can decide how much <strong>to</strong> change N.<br />

You do this by setting the amount in the Step size, C, which can be a positive<br />

or negative number or any <strong>Small</strong> <strong>Basic</strong> expression. Let’s look at some<br />

examples that show you how <strong>to</strong> use this general form of the For loop.<br />

Counting Down by Twos<br />

In this example, the program counts from a starting value (10 in this<br />

case) down <strong>to</strong> 0, subtracting 2 at a time so the program writes the numbers<br />

10, 8, 6, 4, 2, 0 in the text window. Enter and run the program in<br />

Listing 13-5.<br />

1 ' CountDown.sb<br />

2 For N = 10 To 0 Step -2 ' Uses a negative step size<br />

3 TextWindow.WriteLine(N)<br />

4 EndFor<br />

Listing 13-5: Counting down <strong>with</strong> Step<br />

A negative value was used for the Step size (line 2) <strong>to</strong> reduce the value<br />

of the loop counter by 2 after each iteration.<br />

Repeating For Loops 187

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

Saved successfully!

Ooh no, something went wrong!