Constructs

Computer Science AS · Programming. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science AS topics

The idea

Programs are built from sequence, selection and iteration. Selection chooses a path. IF ... THEN ... ELSE tests a condition, and IF statements can be nested for more than two paths. CASE compares one variable with a list of values, which reads more clearly than many nested IFs.

Iteration repeats statements. A count-controlled loop (FOR) is used when the number of repetitions is known. A pre-condition loop (WHILE) tests before the body, so the body may run zero times. A post-condition loop (REPEAT ... UNTIL) tests after the body, so the body runs at least once.

WHILE carries on as long as its condition is TRUE. REPEAT stops when its condition becomes TRUE.

Rules to remember

Common mistake

Thinking a REPEAT ... UNTIL loop is skipped when its condition is already TRUE. The body always runs once before the test is made.

Worked example

What is output by this code?
N ← 20
Count ← 0
WHILE N > 3 DO
   N ← DIV(N, 2)
   Count ← Count + 1
ENDWHILE
OUTPUT Count

  1. 20 > 3 is TRUE: N = DIV(20, 2) = 10, Count = 1.
  2. 10 > 3 is TRUE: N = DIV(10, 2) = 5, Count = 2.
  3. 5 > 3 is TRUE: N = DIV(5, 2) = 2, Count = 3.
  4. 2 > 3 is FALSE, so the loop ends.

Answer: 3

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Programming basicsStructured programming →Take a Computer Science AS test