QBasic: Looping

In programming, loops are used to repeat an instruction for as much as needed. There are a few ways to loop in BASIC:

– IF THEN GOTO
– DO LOOP WHILE/UNTIL
– WHILE WEND

An example of the IF THEN GOTO loop can be found here where we used those commands to check for a triangle. The program will keep on asking for the right values to enter (the ones of a real triangle) thus creating a loop that’s stopped when the right values are entered.

DO LOOP WHILE/UNTIL method

Here’s an example where those commands are used:

[CODE]:
———————————————————————–
CLS

‘A guessing game
try = 0

DO

PRINT “Guess the secret number”
INPUT “Your guess: “; a

‘Generates a number from 1 to 10 every try
x = 10
y = 1
b= INT (RND * (x – y + 1))

‘In case of a correct guess
IF a = b THEN PRINT “You’ve guessed it!”

‘Else: number of tries
try = try + 1
PRINT “Number of tries: “;try

LOOP UNTIL a = b

END
———————————————————————–
[/CODE]

In this example the program will repeat the code in between the DO and LOOP UNTIL command until the user has guessed the secret number, thus the LOOP UNTIL command. If the WHILE command was used, the condition should be changed from a = b to a <> b, because the program would run only when the user guesses the right answer.
The INT (RND * (x – y + 1)) is used for using random numbers in a fixed scope, in this case the larges random number that the computer will generate is 10 and the smallest 1.

WHILE WEND

I’ll use the same example as for the last loop, the guessing game, just corrected a little to fit the WHILE WEND loop:

[CODE:]
———————————————————————–
CLS

try = 0

x = 10
y = 1
b = INT (RND * (x – y + 1))

WHILE a <> b
PRINT “Guess the secret number!”
INPUT “Your guess: “;a

IF a = b THEN PRINT “You’ve guessed it!”

try = try + 1
PRINT “Number of tries: “;try

WEND

END
———————————————————————–
[/CODE]

As you can see the random number generator part is this time excluded from the loop. The reason is that QBasic executes code line by line, and before the WHILE a <> b not a nor b where defined and the program skipped to WEND and END. The loop here is pretty obvious, the code within the loop will execute as long as the WHILE a <> b condition becomes true.

Advertisements

One Response to QBasic: Looping

  1. Nancy says:

    Hi,
    I am in a Qbasic class, and I am just not getting it. Can anyone on here help me with homework?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: