Skip to content
Lesson 3 of 6

Step 1 of 5 · Reading · ~4 min

Learn

Control Flow

If/Then and Loops

By the end of this lesson you can make a program choose between actions with IF and SELECT CASE, repeat work with FOR and DO, and combine a loop with a condition to pick items out of a range.

IF / ELSEIF / ELSE

DIM age AS INTEGER = 15

IF age >= 18 THEN
    PRINT "adult"
ELSEIF age >= 13 THEN
    PRINT "teen"
ELSE
    PRINT "child"
END IF

The block ends with END IF: BASIC uses words where C uses braces. Comparisons are =, <> (not equal), <, >, <= and >=. Equality is a single =; there is no ==. Combine tests with AND, OR and NOT, and give each side of AND/OR its own complete comparison:

IF month = 12 OR month = 1 OR month = 2 THEN PRINT "winter"

IF month = 12 OR 1 OR 2 compiles but does not mean that. There is also a one-line form with no END IF, as above. The classic slip is mixing the two forms: a one-line IF followed by an END IF, or a block IF with the END IF forgotten.

The remainder operator MOD turns "is it a multiple?" into a comparison. A number is a multiple of k when dividing by k leaves nothing over:

IF n MOD 2 = 0 THEN PRINT "even"

Conditions can mix both. A year is a leap year when it divides by 4 but not by 100, or when it divides by 400:

IF (y MOD 4 = 0 AND y MOD 100 <> 0) OR y MOD 400 = 0 THEN PRINT "leap"

SELECT CASE

Comparing one value against many candidates reads better as SELECT CASE, and it accepts ranges and comparisons:

SELECT CASE score
    CASE 90 TO 100
        PRINT "A"
    CASE IS >= 75
        PRINT "B"
    CASE ELSE
        PRINT "below B"
END SELECT

The first matching CASE runs and the rest are skipped, so order them from most specific to most general.

FOR / NEXT

DIM i AS INTEGER
FOR i = 1 TO 5
    PRINT STR(i)
NEXT i

The header, the body and NEXT are separate lines; you cannot squeeze a whole loop onto one line the way C allows. Writing FOR i = 1 TO 5 PRINT i NEXT i on one line is the most common compile error here, and a FOR line you comment out still leaves its NEXT behind to complain.

  1. The end bound is inclusive. FOR i = 1 TO 5 runs five times, for 1, 2, 3, 4 and 5. Programmers from C expect < 5 and lose the last pass.
  2. STEP sets the stride. FOR i = 10 TO 1 STEP -2 visits 10, 8, 6, 4, 2.
  3. A loop can run zero times. With a positive step, if the start is already past the end, the body never executes: FOR i = 1 TO 0 does nothing.

The accumulator pattern

Most loop work means "combine many values into one." Seed a variable before the loop and update it inside. This loop doubles a value four times:

DIM p AS LONGINT = 1
FOR i = 1 TO 4
    p = p * 2
NEXT i
PRINT STR(p)
i    p after the pass
1    2
2    4
3    8
4    16

The seed matters: sums start at 0 and products start at 1, because the seed must be the value that changes nothing. Seed a product with 0 and it stays 0 forever. Print once, after NEXT.

Totals grow faster than you expect. Adding 1 to 100000 gives 5,000,050,000, which does not fit in a 32-bit INTEGER and wraps silently. Declare accumulators that may get large as LONGINT, a 64-bit whole number.

DO / LOOP

When you do not know the count in advance, loop on a condition:

DIM n AS INTEGER = 1000
DIM steps AS INTEGER = 0
DO WHILE n > 0
    n = n \ 2
    steps = steps + 1
LOOP
PRINT STR(steps)     ' 10

DO WHILE tests before each pass. DO ... LOOP UNTIL cond tests after the pass, so it always runs at least once. EXIT FOR and EXIT DO leave the innermost loop of that kind early.

Common mistakes

  • Counting a value twice. If two conditions can both be true for the same number, two separate IF statements that each add to the total add it twice; one IF with OR adds it once.
  • Stopping one short. With an inclusive bound, writing TO n - 1 drops the last value, and the answer is wrong by exactly that value.
  • Seeding wrongly: a total that starts at 1, or a product that starts at 0.
  • Printing inside the loop, which outputs every running total instead of one answer.

Your exercise

Read N and print the sum of the numbers from 1 to N that are divisible by 3 or by 5. The starter reads N, declares a LONGINT total and prints it through STR(); the loop and the test in between are yours.

Up nextSubs and FunctionsSubs, Functions, Arrays

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…