Teachers' Portal  /  A-Level Computer Science 9618  /  Programming  /  Selection and iteration constructs
Lesson pack · A-Level Computer Science 9618 · 11.2 · AS Level

Selection and iteration constructs

Choose a path, then repeat. Selection lets a program choose which statements to run; iteration makes it repeat them.

Student lesson Lab, full screen
At a glance

The shape of the lesson

Topic
Programming
Syllabus reference
Cambridge International AS and A Level Computer Science 9618, 11.2
Level
AS Level
Duration
45 minutes, lab-led; stretches to a 60 minute block (see the contingency notes)
Position in topic
Lesson 2 of 4 in Programming; follows Variables, constants and built-in functions; leads into Procedures and functions
Central model
Fig. 1: where each loop tests its condition decides the fewest times its body can run
Cooperative structure
Assessment
Stage 1 check and the exam-style plenary from the student lesson, plus the worksheet as the exit task
Learning objectives

By the end of the lesson, learners can

Section by section
  • IF, ELSE and nesting: An IF statement chooses between two paths.
  • The CASE structure: When one variable is compared with several possible values or ranges, CASE is clearer than a chain of nested IFs.
  • Three kinds of loop: Step through the loop programs in the lab (FOR, WHILE, REPEAT UNTIL and nested FOR with STEP) and watch the trace table fill.
Key points to leave on the board
  • IF: THEN on the IF line, one ENDIF per IF; check the boundary values.
  • CASE: one variable, values or ranges, first match wins, OTHERWISE last.
  • FOR = known count; REPEAT = at least once; WHILE = maybe zero times.
  • Justify a loop by saying why its test position suits this problem, not just what the loop is.
The core visual model

One picture every idea returns to

Selection uses IF ... THEN ... ELSE ... ENDIF (which can be nested) or CASE OF ... OTHERWISE ... ENDCASE, whose clauses are tested in order until one matches. Iteration has three forms: a count-controlled loop (FOR ... NEXT) repeats a known number of times; a post-condition loop (REPEAT ... UNTIL) tests at the end, so it always runs at least once; a pre-condition loop (WHILE ... ENDWHILE) tests at the start, so it may run zero times.

FOR (count)WHILE (pre)REPEAT (post) i ← 1i ≤ 10? bodyi ← i + 1 cond?body bodycond? TRUEFALSE TRUEFALSE FALSETRUE runs a fixed number of timesmay run 0 timesruns at least once
Fig. 1: where each loop tests its condition decides the fewest times its body can run
Lesson sequence

Forty-five minutes, phase by phase

TimePhaseWhat happens in the roomGrouping
0 to 5 minHook: predictOpen with the question in the title, Choose a path, then repeat.. Selection lets a program choose which statements to run; iteration makes it repeat them. Put the figure on the board: it is the one picture every idea in the lesson returns to.Whole class, then pairs
5 to 13 minTeach and check: IF, ELSE and nestingAn IF statement chooses between two paths. Model the worked example Dry-run the delivery charge on the board, one line at a time. Your turn: What is output for Weight 6.0 and Express TRUE?Whole class, then pairs
13 to 21 minTeach and check: The CASE structureWhen one variable is compared with several possible values or ranges, CASE is clearer than a chain of nested IFs. Model the worked example Which clause runs? on the board, one line at a time. Your turn: A programmer adds the clause 60 TO 100: Grade ← 'S' as the very first clause. Which grades can now never be given?Pairs
21 to 30 minTeach and check: Three kinds of loopStep through the loop programs in the lab (FOR, WHILE, REPEAT UNTIL and nested FOR with STEP) and watch the trace table fill. Project tab 1 of the lab (Sequence, selection and iteration with a trace table) and let a student drive it while the class predicts. Model the worked example Trace a WHILE loop on the board, one line at a time. Your turn: What happens if 8 is input to the WHILE program, and why could a REPEAT loop not give the same result?Think-Pair-Share
30 to 36 minCheckThe four Stage 1 questions from the student lesson, answered on mini whiteboards or by show of fingers. Re-teach the one most get wrong.Individual, then whole class
36 to 43 minPlenaryThe exam-style questions from Stage 2, one at a time: thirty seconds alone, then a random call. The feedback lines in the key give the examiner's wording.Individual, random call
43 to 45 minExit and homeworkSet the worksheet below (6 questions, 23 marks). Learners self-assess against the objectives before they leave.Individual
Timing and contingency

Protect the parts that carry the learning

The sequence carries about fifty minutes of material, so the lab is driven by one student while the class predicts rather than explored freely. Times are a guide.

Protected: the check at 30 minutes. It is the only individual read on whether the key idea landed, and it is not cut.

Cut first if the build overruns: the last check in Three kinds of loop, never the check or the plenary.

In a 60 minute block: run worksheet questions 1 to 3 in class as a Rally Coach set and model both the hardest worked example and its check live.

Running the cooperative task

Think-Pair-Share

Pose the question, give thirty seconds of silent thinking, then a minute to compare with a partner before a few pairs share with the class. The silent minute is the part that cannot be cut.

The full structure, with its variations and the other twelve, is on the cooperative-learning page.

Examiner traps to pre-empt

What to head off, and how

Trap learners fall intoTeaching move that pre-empts it
Check boundary values.Changing <= to < moves a 2.0 kg parcel into the next price band, and examiners test exactly that value.
CASE stops at the first match.Overlapping ranges are not an error, but every value is caught by the earlier range, so the later clause is dead code.
The UNTIL condition is the condition to stop; the WHILE condition is the condition to keep going.Converting one loop into the other means reversing the condition.
Worksheet

Selection and iteration constructs: worksheet

6 questions, 23 marks. Written in the style of the papers; no past paper question is reproduced.

NameClassDate
Q1 · explain[3 marks]

Explain the difference between a pre-condition loop and a post-condition loop, giving a suitable use for each.

Q2 · trace[4 marks]

The inputs are 4, 7, 10, 0, 3. Complete a trace table and state the output.

Total ← 0
Count ← 0
REPEAT
    INPUT Value
    IF Value MOD 2 = 0 THEN
        Total ← Total + Value
    ENDIF
    Count ← Count + 1
UNTIL Value = 0 OR Count = 5
OUTPUT Total, " ", Count
Q3 · write[4 marks]

Day holds an integer. Write a CASE structure that outputs Weekday for 1 to 5, Weekend for 6 or 7 and Invalid day for any other value.

Q4 · write[5 marks]

A museum charges 5.00 for visitors under 12, 7.00 for ages 12 to 17 and 10.00 for ages 18 and over, except that students aged 18 or over pay 8.00. Write pseudocode using nested IF statements that inputs Age (INTEGER) and Student (BOOLEAN) and outputs the price.

Q5 · analysis[3 marks]

Choose the most suitable loop for each task and justify your choice.

(a) Output the 12 times table from 1 × 12 to 12 × 12.
(b) Keep asking for a PIN until the correct PIN is entered.
(c) Halve a value until it is below 1, where the value input may already be below 1.

Q6 · convert[4 marks]

Rewrite this loop using a WHILE loop so that it produces the same result, and state the final value of Total.

Total ← 0
FOR Index ← 1 TO 20 STEP 2
    Total ← Total + Index
NEXT Index
Answer key and marking notes
Q1 · 3 marks
  • A pre-condition loop tests its condition before the body, so the body may run zero times.
  • A post-condition loop tests its condition after the body, so the body always runs at least once.
  • Uses: pre-condition for reading a file that may be empty (WHILE NOT EOF); post-condition for validating input that must be entered at least once.
Q2 · 4 marks
  • Value 4: even, Total 4, Count 1; Value 7: odd, Total 4, Count 2.
  • Value 10: even, Total 14, Count 3.
  • Value 0: 0 MOD 2 = 0, so Total stays 14 (adds 0), Count 4; Value = 0 is TRUE so the loop stops.
  • Output: 14 4 (the input 3 is never read).
Q3 · 4 marks
  • CASE OF Day ... ENDCASE
  • 1 TO 5 : OUTPUT "Weekday"
  • 6 TO 7 : OUTPUT "Weekend" (or two clauses 6 and 7)
  • OTHERWISE : OUTPUT "Invalid day" as the last clause.
Q4 · 5 marks
  • INPUT Age and INPUT Student.
  • IF Age < 12 THEN Price ← 5.00 ELSE ...
  • nested IF Age <= 17 THEN Price ← 7.00 ELSE ...
  • nested IF Student = TRUE THEN Price ← 8.00 ELSE Price ← 10.00, with three correctly matched ENDIFs.
  • OUTPUT Price.
Q5 · 3 marks
  • (a) FOR loop: the number of repetitions (12) is known in advance.
  • (b) REPEAT ... UNTIL: the PIN must be input at least once before it can be checked.
  • (c) WHILE loop: the condition is tested first, so if the value is already below 1 the body is not run.
Q6 · 4 marks
  • Total ← 0 and Index ← 1 before the loop.
  • WHILE Index <= 20 ... ENDWHILE.
  • Inside: Total ← Total + Index then Index ← Index + 2.
  • Total = 1 + 3 + 5 + ... + 19 = 100.
Quiz

6 multiple-choice questions on this lesson

From the topic question bank. Assign them in the app for a marked score in your gradebook, or run the topic as a class game.

Q11 mark

A program must keep asking for a password until the correct one is entered. Which loop is most suitable?

  • AREPEAT ... UNTIL, because the password must be input at least once before it can be checked
  • BWHILE ... ENDWHILE, because the condition is tested before the password has been input
  • CFOR ... NEXT, because the number of attempts needed is known before the loop starts
  • DCASE ... ENDCASE, because each wrong password needs a different message to be output
Q21 mark

What is output by this loop?

FOR Count ← 20 TO 3 STEP -4
    OUTPUT Count
NEXT Count

  • A20, 16, 12, 8, 4
  • B20, 16, 12, 8
  • C20, 16, 12, 8, 4, 0
  • D16, 12, 8, 4
Q31 mark

This CASE structure is run, first with Speed = 55 and then with Speed = 125.

CASE OF Speed
    0 TO 30 : Band ← "Slow"
    31 TO 60 : Band ← "Medium"
    50 TO 120 : Band ← "Fast"
    OTHERWISE : Band ← "Error"
ENDCASE
What is Band each time?

  • A"Medium", then "Error"
  • B"Fast", then "Error"
  • C"Medium", then "Fast"
  • D"Fast", then "Fast"
Q41 mark

This code is run with Age = 13, then with Age = 65.

IF Age < 13 THEN
    Price ← 4
ELSE
    IF Age >= 65 THEN
        Price ← 5
    ELSE
        Price ← 9
    ENDIF
ENDIF
OUTPUT Price
What is output each time?

  • A9, then 5
  • B4, then 5
  • C9, then 9
  • D4, then 9
Q51 mark

What is output by this program?

N ← 1
Count ← 0
WHILE N < 100
    N ← N * 3
    Count ← Count + 1
ENDWHILE
OUTPUT Count, " ", N

  • A5 243
  • B4 81
  • C5 81
  • D4 243
Q61 mark

A programmer wants to rewrite this validation loop using a WHILE loop, so that it behaves the same for every input.

REPEAT
    INPUT Mark
UNTIL Mark >= 0 AND Mark <= 100
Which version is correct?

  • AINPUT Mark, then WHILE Mark < 0 OR Mark > 100 containing INPUT Mark, then ENDWHILE
  • BINPUT Mark, then WHILE Mark >= 0 AND Mark <= 100 containing INPUT Mark, then ENDWHILE
  • CINPUT Mark, then WHILE Mark < 0 AND Mark > 100 containing INPUT Mark, then ENDWHILE
  • DWHILE Mark < 0 OR Mark > 100 containing INPUT Mark, then ENDWHILE, with no input before it
Quiz key
Q1: A

The password has to be entered before it can be compared, so the body must run at least once: a post-condition REPEAT ... UNTIL loop. A WHILE loop tests first, so it needs an extra INPUT before the loop. A FOR loop needs a known count, but nobody knows how many attempts will be needed. CASE is selection, not iteration, so it cannot repeat anything.

Q2: A

Count takes 20, 16, 12, 8 and 4; the next value, 0, is past 3, so the loop ends after 5 passes. Stopping at 8 forgets that 4 is still not past 3. Including 0 ignores the end value. Starting at 16 subtracts the step before the first pass, but the first pass uses the start value.

Q3: A

55 matches 31 TO 60 first, so Band is "Medium" and the overlapping 50 TO 120 clause is never reached. 125 matches no range, so OTHERWISE gives "Error". "Fast" for 55 assumes the last matching clause wins. "Fast" for 125 forgets that 120 is the top of that range.

Q4: A

13 < 13 is FALSE, so the ELSE runs; 13 >= 65 is FALSE, so Price is 9. For 65, 65 < 13 is FALSE and 65 >= 65 is TRUE, so Price is 5. Outputting 4 for 13 treats < as <=. Outputting 9 for 65 treats >= as >.

Q5: A

N goes 3, 9, 27, 81, 243 and Count goes 1 to 5. After the fourth pass N is 81, and 81 < 100 is still TRUE, so a fifth pass makes N 243; then 243 < 100 is FALSE and the loop ends. "4 81" stops one pass early, as if the test were N * 3 < 100. "5 81" and "4 243" mix the count from one pass with N from another.

Q6: A

The WHILE condition must be the opposite of the UNTIL condition: NOT (Mark >= 0 AND Mark <= 100) is Mark < 0 OR Mark > 100, and an INPUT before the loop gives Mark a value to test. Keeping the original condition would repeat only for valid marks. Using AND can never be TRUE, since no mark is both below 0 and above 100, so invalid marks are accepted. Without the first INPUT, Mark is tested before it has been given a value.

Lab and demo

What to project

The student lesson embeds these tabs. Open them full screen on the projector; every slider has a drag handle on the stage.

Slides

Slides for this lesson

A projectable deck for every pack is on the way. Until then, present the student lesson full screen: its sections, figure and lab tabs follow the same order as the plan above.

Also for this topic

Everything else you can use

Original work by the TheLucidSTEM team. The worksheet items are written in the style of the papers; no past paper question is reproduced.
Previous lessonVariables, constants and built-in functions