Chapter 3: Flow Control Blocks and Loops
|
3.1 |
Introduction
Control blocks and Loops are fundamental in all procedural languages. Functional languages like PROLOG or LISP do not require any loops, everything is done recursively through functions (hence the label, Functional Programming). Anyway, in BASIC, recursion is bad (too much stack space is wasted), so if you're thinking about optimization, use loops instead of deep recursion. |
3.2 |
Using IF..THEN..ELSE
Perhaps the most useful control flow statement, you'll be using this in about every program you will write. Here's a very common, yet bad programming style:
IF I=100 THEN N=10:M=20:J=30 Although most BASIC programmers will know what this does, it's not very obvious or logical. Just think about it, the colon ':' is a line splitter, which means the above statement should translate to:
IF I=100 THEN N=10
M=20
J=30 However, we know this isn't true. Anyway, the preferred approach is to use IF..END IF
|
3.3 |
When not to use IF..THEN..ELSE
IF I=1 THEN
N = 20
ELSEIF I=2 THEN
N = 30
ELSEIF I=3 THEN
N = 40
ELSE
: You get the picture, this looks brutal when you have over 10 of these or more. That's why QBasic supports the SELECT CASE statement. Here's what the above program would look like using SELECT CASE:
SELECT CASE I
CASE 1
N = 20
CASE 2
N = 30
CASE 3
N = 40
CASE ELSE
N = 50
END SELECT This is just good programming style, but it's up to you whether you want to conform or not. The SELECT CASE statement is more useful in other situations, especially when dealing with ranges.
|
3.4 |
The many faces of LOOPS
QBasic supports the DO..LOOP and WHILE..WEND control loops. So how do you know when to use DO or WHILE? Perhaps an example would help:
I = 1000
DO
I = I + 1
LOOP UNTIL I < 1000
I = 1000
WHILE I < 1000
I = I + 1
WEND In the DO..LOOP, I = I + 1 is called, whether this is what you wanted is another story, but in the WHILE..WEND loop, I = I + 1 is not called. As you can see, if you want to test a condition before you enter the loop, use WHILE, otherwise use DO..LOOP.
|
3.5 |
FOR..NEXT Loop
If you need to repeat a sequence of statements a specific number of times, use the FOR..NEXT loop. This has many possible uses, for example:
FOR I=1 to 3
PRINT I
NEXT I Okay, that's not so useful, but as an exercise, use two FOR..NEXT Loops to achieve this result:
1 2 3
4 5 6
7 8 9 You should be a pro once you figure this one out.
|
|
|