Programming concepts - AQANested iteration and selection

Programs are designed using common building blocks, known as programming constructs. These programming constructs form the basis for all programs.

Part ofComputer ScienceComputational thinking and problem solving

Nested iteration and selection

Nested iteration

Iteration can also be . This program uses two definite FOR loops, one within another, to print out the times table for all numbers from one to ten:

FOR x ← 1 TO 10 FOR y ← 1 TO 10 result ← y * x OUTPUT y + " * " + x + " = " + result ENDFOR
ENDFOR

For every iteration of x, y is iterated ten times.

Nested iteration isn't limited to FOR loops. A WHILE loop can be nested in a FOR loop and a FOR loop can be nested in a WHILE loop.

Nested selection

When using , the number of possible paths at a decision point can be increased by including one selection within another.

This program uses nested selection:

age ← int(input("How old are you? ")
if age > 16 then OUTPUT("You are old enough to drive a car and ride a moped!")
ELSE if age == 16 then OUTPUT("You are old enough to ride a moped!") ELSE OUTPUT("Come back when you are older!") ENDIF
ENDIF

Here, there are two conditions that may be tested, resulting in three possible paths to follow. The second condition is only tested if the result of the first test is FALSE.

Nested selection can be built up over and over to include many possibilities and paths for a program to follow. It allows for complex decisions to be made.