15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

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

208<br />

Looping at Least Once with the DO Loop<br />

The first line defines the Answer variable as a string data type. The<br />

second line asks the user <strong>for</strong> a password and stores that answer in the<br />

Answer variable.<br />

The WHILE loop first checks if the Answer variable is SECRET. If not, the<br />

loop runs the two commands that print Invalid password and then asks<br />

Enter password: on-screen once more.<br />

Whatever reply the user types gets stored in the Answer variable. Then the<br />

WHILE loop checks this Answer variable again be<strong>for</strong>e running.<br />

You can make a WHILE loop count like a FOR-NEXT loop. Suppose you had<br />

the following FOR-NEXT loop:<br />

FOR I = 10 DOWNTO 1<br />

PRINT I<br />

NEXT I<br />

PRINT “BLASTOFF!”<br />

The equivalent WHILE loop might look like this:<br />

I = 10<br />

WHILE (I >= 1)<br />

PRINT I<br />

I = I - 1<br />

WEND<br />

PRINT “BLASTOFF!”<br />

Although the WHILE loop can count, notice that it takes more lines of code<br />

to do so, and the WHILE loop isn’t as easy to understand as the FOR-NEXT<br />

loop. If you need a loop to run a fixed number of times, use the FOR-NEXT<br />

loop. If you aren’t sure how many times you need a loop to run, use the<br />

WHILE loop.<br />

Looping at Least Once with the DO Loop<br />

Be<strong>for</strong>e a WHILE loop runs, it checks a Boolean expression to see if it’s True<br />

or False. If this Boolean expression is False, the WHILE loop never runs at<br />

all. What if you want to insure that the loop runs at least once? In that case,<br />

you must use a DO loop.<br />

A DO loop acts like an upside-down WHILE loop. First the DO loop runs once<br />

and then it checks a Boolean expression. A typical DO loop looks like this:<br />

DO<br />

Command<br />

Command to change the Boolean expression<br />

LOOP WHILE (True or False Boolean expression)

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

Saved successfully!

Ooh no, something went wrong!