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.

This piece of code simply says, “As long as ans is not equal <strong>to</strong> num, run<br />

the statement(s) between the While and the EndWhile keywords.”<br />

First, the test condition (ans num) is evaluated. If it’s true, the program<br />

runs the statements in the loop’s body and keeps repeating until the<br />

condition becomes false. When the test condition becomes false, the loop<br />

ends, and the program moves <strong>to</strong> the next statement after the EndWhile keyword.<br />

The flowchart in Figure 14-1 illustrates how the While loop works.<br />

Condition?<br />

False<br />

True<br />

Execute statements in<br />

the body of the<br />

While loop.<br />

Move <strong>to</strong> the statement after<br />

the EndWhile keyword.<br />

Figure 14-1: Flowchart of the While loop<br />

In the number-guessing game, when the program runs line 4 for<br />

the first time, the condition (ans num) is true (because we know that<br />

num can’t be 0), and the loop runs the statements in its body (lines 5–13).<br />

During each iteration of the loop, the player is prompted <strong>to</strong> enter a guess<br />

(line 5), which is saved in<strong>to</strong> the variable ans (line 6). The code then compares<br />

the player’s guess <strong>with</strong> the secret number. If the player guessed correctly<br />

(line 7), the code displays Good Job! You get sprinkles! and moves <strong>to</strong><br />

the statement after EndIf. In this example, it finds EndWhile, which takes your<br />

program back <strong>to</strong> check the condition of the While loop. Because ans is now<br />

equal <strong>to</strong> num, the test condition is false and the While loop terminates, ending<br />

the program (because there are no statements after EndWhile).<br />

If the player’s guess was incorrect, the code checks whether the guess<br />

was higher than the secret number (line 9). If it’s higher, the program displays<br />

Too High. Lower your standards. Then the loop goes for another round.<br />

If the player’s guess is lower than the secret number (the Else statement<br />

on line 11), the program displays Too Low. Aim for the stars! (line 12) and<br />

starts another round.<br />

Here is an example of a rather lucky user playing the game:<br />

Enter your guess [1-100]: 50<br />

Too High. Lower your standards.<br />

Enter your guess [1-100]: 25<br />

Too Low. Aim for the stars!<br />

Enter your guess [1-100]: 37<br />

Good Job! You get sprinkles!<br />

Play this game several times <strong>to</strong> see how it works!<br />

Creating Conditional While Loops 197

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

Saved successfully!

Ooh no, something went wrong!