UNIHIVE

Study Hub UNIPORT CSC 180.1

CSC 180.1 · Introduction to Computer Science and BASIC Programming

Control statements: decisions and loops

GOTO, IF...THEN...ELSE, FOR...NEXT with STEP, WHILE...WEND and nested loops.

Our notes

1 min read

GOTO

GOTO 100 jumps unconditionally to line 100. Too many GOTOs make "spaghetti code"; use it sparingly.

IF...THEN...ELSE

10 INPUT "SCORE"; S
20 IF S >= 50 THEN PRINT "PASS" ELSE PRINT "FAIL"
30 END
IF S < 0 THEN 10 jumps back to line 10 (old style, a conditional GOTO).

Grading example (multi-way decision)

10 INPUT S
20 IF S >= 70 THEN G$ = "A" : GOTO 70
30 IF S >= 60 THEN G$ = "B" : GOTO 70
40 IF S >= 50 THEN G$ = "C" : GOTO 70
50 IF S >= 45 THEN G$ = "D" : GOTO 70
60 G$ = "F"
70 PRINT "GRADE "; G$
80 END
S = 63 prints GRADE B. (Use your own university's grade scale.)

FOR...NEXT loops

10 LET SUM = 0
20 FOR I = 1 TO 10
30 LET SUM = SUM + I
40 NEXT I
50 PRINT SUM
60 END
Prints 55. STEP changes the increment: FOR I = 10 TO 1 STEP -1 counts down; FOR I = 2 TO 20 STEP 2 gives even numbers.

Worked example: factorial

10 INPUT N
20 LET F = 1
30 FOR K = 1 TO N
40 LET F = F * K
50 NEXT K
60 PRINT N; "! ="; F
70 END
N = 5 prints 5! = 120.

WHILE...WEND (QBasic, many dialects)

Repeats while a condition is true; the number of passes need not be known.
10 LET N = 1
20 WHILE N < 100
30 LET N = N * 2
40 WEND
50 PRINT N
N goes 2, 4, ... 64, 128: prints 128.
QBasic also has DO...LOOP UNTIL.

Nested loops

A loop inside another; the inner loop finishes all its passes for each pass of the outer one. A multiplication table:
10 FOR I = 1 TO 3
20 FOR J = 1 TO 3
30 PRINT I * J;
40 NEXT J
50 PRINT
60 NEXT I
Prints 1 2 3 / 2 4 6 / 3 6 9. Inner loops must close before outer ones (NEXT J before NEXT I).

Exams usually ask

  • Write programs with IF...THEN and FOR...NEXT (sum of a series, factorial, grades, largest of N numbers).
  • Give the output of a given loop.
  • Distinguish counter-controlled from condition-controlled loops.

Common mistake

Crossing nested loops (NEXT I before NEXT J), or forgetting to reset a total to 0 before a loop.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All CSC 180.1 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.