Programming fundamentals - OCRNesting

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

Part ofComputer ScienceComputational thinking, algorithms and programming

Nesting

occurs when one programming construct is included within another. Nesting allows for powerful, yet simple programming. It reduces the amount of code needed, while making it simple for a programmer to and edit.

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 print("You are old enough to drive a car and ride a moped!")
else if age == 16 then print("You are old enough to ride a moped!") else print("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.

Nested iteration

can also be nested. This program uses two count-controlled for next, 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 print(y, " * ", x, " = ", result) next y
next x

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

This program uses condition-controlled whileendwhile loops, one within another, to print out the times table for all numbers from one to ten:

x = 1
y = 1
while x < 11: while y < 11: result = y * x print(y, " * ", x, " = ", result) y = y + 1 y = 1 x = x + 1

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