Computer Science Education | Programming Language Tutorials For Beginners

QBASIC TUTORIAL 10 - LOOPS

"Loops" make it easier to do an action multiple times. There are at least four types of loops:
IF...GOTO, WHILE...WEND, DO...LOOP, and FOR...NEXT.

IF...GOTO
This program uses IF...GOTO to create a loop:

x = 10
Start:
PRINT x
x = x + 1 (This adds 1 to x)
IF x < 15 THEN GOTO start


Output:
10
11
12
13
14


WHILE...WEND
The WHILE...WEND commands continue a loop until a specified expression is false.

While Loop Syntax:

WHILE <Condition>
Do Something
WEND

To use WHILE...WEND:
1. Place an expression after WHILE
2. Enter a list of commands
3. Place WEND at the end

Run the following:

x = 10
WHILE x < 15
PRINT x
x = x + 1
WEND


Output (same as in previous example):

10
11
12
13
14

DO...LOOP
DO...LOOP is exactly the same as WHILE...WEND, except it has at least two slight advantages. With DO...LOOP you can:

1. Loop until an expression is true
2. Loop at least one time regardless of whether the expression is true or not.

Do Loop Syntax:

DO WHILE <condition>
Do Something
LOOP

To use DO...LOOP:
1. Specify whether the loop continues "while" the expression is true or "until" the expression is true, using the WHILE and UNTIL statements, respectively.
2. Place an expression after WHILE/UNTIL
3. Enter a list of commands
4. Place LOOP at the end

The following uses the WHILE statement:

x = 10
DO WHILE x < 15
PRINT x
x = x + 1
LOOP

This program uses the UNTIL statement:

x = 10
DO UNTIL x = 15
PRINT x
x = x + 1
LOOP


They both have the same output:

10
11
12
13
14

If you place the expression at the end of the loop instead, the program goes through the loop at least once.

x = 32
DO
PRINT x
x = x + 1
LOOP WHILE x < 5

This is the output because the loop was only gone through one time:

32

FOR...NEXT
FOR...NEXT provides an easier way to create a loop.

For Loop Syntax:

FOR Counter = start TO End
Do Something
Next Counter

Run this program:

FOR x = 1 TO 5
PRINT x
NEXT x


Output:
1
2
3
4
5


TIP: The X after NEXT is optional (unless you have a loop within a loop).

Also, you can use the STEP attribute to specify how much X will be increased each time through the loop.

FOR x = 1 TO 5 STEP 2
PRINT x
NEXT x

Output:
1
3
5

STOPPING LOOPS
To stop a loop prematurely, use the EXIT command, followed by either FOR or DO.

FOR x = 1 TO 5
PRINT x
IF (x = 3) THEN EXIT FOR
NEXT x

Output:
1
2
3

(NOTE: This command only works with the DO...LOOP and FOR...NEXT commands, not with WHILE...WEND or IF...GOTO.)

Share:

No comments:

Post a Comment

Popular Posts

Elitcode - Learning Start Here

Elitcode Blog Archive