Kenneth Leroy Busbee

Overview

Nested for loops places one for loop inside another for loop. The inner loop is repeated for each iteration of the outer loop.

Discussion

Nested Control Structures

We are going to first introduce the concept of nested control structures. Nesting is a concept that places one item inside of another. Consider:

if expression
    true action
else 
    false action

This is the basic form of the if then else control structure. Now consider:

if age is less than 18
    you can't vote
    if age is less than 16
        you can't drive
    else
        you can drive
else
    you can vote
    if age is less than 21
        you can't drink 
    else
        you can drink

As you can see we simply included as part of the “true action” a statement and another if then else control structure. We did the same (nested another if then else) for the “false action”. In our example, we nested if then else control structures. Nesting could have an if then else within a while loop. Thus, the concept of nesting allows the mixing of the different categories of control structures.

Many complex logic problems require using nested control structures. By nesting control structures (or placing one inside another) we can accomplish almost any complex logic problem.

An Example – Nested for loops

Here is an example of a 10 by 10 multiplication table:

         1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10 |
     -------------------------------------------------------------
   1 !   1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10 |
   2 !   2 |   4 |   6 |   8 |  10 |  12 |  14 |  16 |  18 |  20 |
   3 !   3 |   6 |   9 |  12 |  15 |  18 |  21 |  24 |  27 |  30 |
   4 !   4 |   8 |  12 |  16 |  20 |  24 |  28 |  32 |  36 |  40 |
   5 !   5 |  10 |  15 |  20 |  25 |  30 |  35 |  40 |  45 |  50 |
   6 !   6 |  12 |  18 |  24 |  30 |  36 |  42 |  48 |  54 |  60 |
   7 !   7 |  14 |  21 |  28 |  35 |  42 |  49 |  56 |  63 |  70 |
   8 !   8 |  16 |  24 |  32 |  40 |  48 |  56 |  64 |  72 |  80 |
   9 !   9 |  18 |  27 |  36 |  45 |  54 |  63 |  72 |  81 |  90 |
  10 !  10 |  20 |  30 |  40 |  50 |  60 |  70 |  80 |  90 | 100 |

We might also see that the answers could be designed as a collection of cells (each cell being exactly six spaces wide). The pseudocode to produce part of the table is:

For row = 1, row <= 3, row += 1
    For column = 1, column <= 3, column += 1
        Output row * column
        Output "\t"
    Output "\n"

Key Terms

complex logic
Often solved with nested control structures.

References

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Kenneth Leroy Busbee is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book