Nesting

<< Previous: Iteration Next: Subroutines >>

About nesting

Nesting is placing one programming structure inside another. This could be as simple as having lines of code in sequence nested inside an if statement but it also includes far more complex structures. This might include selection nested inside an iterative structure, or iteration nested inside iteration.

Nested iteration

Nesting two loops can allow for some very powerful code to be created very efficiently. Take a look at the example below. By using two for loops we have created a very short piece of code that would output the entire times tables for 1 to 10. The first loop starts and i is 1, then the second loop starts and j is 1, so the output is 1x1=1. Next j becomes 2 and the output is 1x2=2. The inner loop will continue to increment until it is complete at which point i is 1 and j is 10 and the output is 1x10=10. This means we have done one loop of the outside loop. Therefore i becomes 2. A new inner loop is created with j at 1 and the output is 2x1=2. This carries on until the outer loop has run with i as 10.

Solving problems

Nesting is key to solving complex problems. Consider for instance the standard process for logging into an account that involves trying to enter the correct password but also normally contains a limit to the number of times. By nesting selection inside iteration we can achieve this. The keen-eyed may have spotted the use of the logical operator 'or' in the loop condition. This will be explained later in this unit.

Knowledge check


Questions:
Correct:

Question text


<< Previous: Iteration Next: Subroutines >>

© All materials created by and copyright S.Goff