nestingIncluding one programming construct within another. 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 debugThe process of finding and correcting programming errors. and edit.
Nested selection
When using selectionA decision within a computer program when the program decides to move on based on the results of an event., 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
iterationThe repetition of a block of statements within a computer program. can also be nested. This program uses two count-controlled for nextloopA method used in programming to repeat a set of instructions., 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.