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.

In simpler words

Programs use three building blocks: do steps in order, choose a path, and repeat. IF chooses between paths. CASE checks one variable against a list. FOR repeats a known number of times. WHILE checks first, so it may not run at all. REPEAT UNTIL checks at the end, so it always runs at least once.

An everyday comparison

WHILE is like checking the fridge before cooking: if there is no food, you do not start. REPEAT UNTIL is like tasting soup after adding salt: you add some, taste, and stop when it is right, so you always add at least once. FOR is like doing ten press-ups. The comparison stops working because a loop whose condition never changes runs forever.

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.

In the exam

Choose the construct and justify it with the right phrase: FOR when the number of repetitions is known; WHILE, a pre-condition loop, when the body may need to run zero times; REPEAT UNTIL, a post-condition loop, when it must run at least once. Write complete syntax with closing keywords such as ENDIF, ENDWHILE, ENDCASE and NEXT. Use CASE with OTHERWISE for one variable with many values. Make sure something in the loop body changes the condition.

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