Ad Banner Placeholder

Cambridge IGCSE Computer Science · 0478

Topic 8: Programming — Part 2

Control Structures

Three control structure principles

All algorithms can be built from three fundamental control structures:

Sequence
Instructions are executed one after another in order from top to bottom.
Selection
The program chooses which path to follow based on a condition (e.g. IF or CASE).
Iteration
A block of code is repeated while a condition is met or for a fixed number of times (e.g. FOR, WHILE, REPEAT UNTIL).

Selection — IF and CASE

Nested IF example

The following pseudocode assigns a grade based on a score using nested IF statements:

IF Score >= 80
  THEN
    OUTPUT "Grade A"
  ELSE
    IF Score >= 50
      THEN
        OUTPUT "Grade B"
      ELSE
        OUTPUT "Grade C"
    ENDIF
ENDIF

CASE example

CASE is more efficient than multiple IFs when checking a single variable against many discrete values:

CASE OF Move
  'W' : Position ← Position - 10
  'S' : Position ← Position + 10
  OTHERWISE OUTPUT "Invalid Input"
ENDCASE

Iteration — FOR, WHILE, and REPEAT UNTIL

FOR loop with STEP

A FOR loop repeats a fixed number of times. STEP controls the increment:

FOR Index ← 1 TO 10 STEP 2
  OUTPUT Index
NEXT Index

WHILE loop (pre-condition)

The condition is checked before each repetition. If the condition is false initially, the loop body may never run:

WHILE Number > 0 DO
  Number ← Number - 1
ENDWHILE

REPEAT UNTIL loop (post-condition)

The condition is checked after each repetition, so the loop body runs at least once:

REPEAT
  INPUT Guess
UNTIL Guess = Secret

Totalling and counting

Combine both patterns in one loop — initialise Total and Count to zero before the loop starts:

DECLARE Total : REAL
DECLARE Count : INTEGER
Total ← 0
Count ← 0
FOR i ← 1 TO 5
  INPUT Value
  Total ← Total + Value
  IF Value > 50 THEN
    Count ← Count + 1
  ENDIF
NEXT i
OUTPUT "Total is: ", Total
OUTPUT "Count of items over 50 is: ", Count

0/15

Ad Banner Placeholder