10B. Nested Loops and Nested Loop Emulation


Nested loops

Loops are nested when one loop is inside another. For example, if nestdemo is defined by

  void nestdemo()
  {
    printf("  i  j\n");
    int i = 1;
    while(i <= 4)
    {
      int j = 1;
      while(j <= 4)
      {
         printf("%3i%3i\n", i, j);
         j++;
      }
      i++;
    }

then nestdemo() prints

  i  j
  1  1
  1  2
  1  3
  1  4
  2  1
  2  2
  2  3
  2  4
  3  1
  3  2
  3  3
  3  4
  4  1
  4  2
  4  3
  4  4

The coding standards for this course require each function to contain no more than one loop. As a consequence, you cannot directly write nested loops. What should you do? Pull the inner loop out into a separate function.

  void dorow(int i)
  {
    int j = 1;
    while(j <= 4)
    {
       printf("%3i%3i\n", i, j);
       j++;
    }
  }

  void nestdemo()
  {
    int i = 1;
    while(i <= 4)
    {
      dorow(i);
      i++;
    }
  }  

Nested loop emulation

Upon seeing that the standards disallow directly nested loops, some students try using nested loop emulation, which uses one loop to emulate two nested loops. Typically, there are two control variables (say, i and j) that are managed in the loop body so that the values of i and j change in a way that is like the example above. Here is conversion of the above nested loops into a single emulating loop.

  int i = 1;
  int j = 1;
  while(i <= 4)
  {
    printf("%3i%3i\n", i, j);
    j++;
    if(j == 5)
    {
      j = 1;
      i++;
    }
  }

That is not an improvement. It is much more difficult to understand than the original two nested loops, and it is not an acceptable thing to do. The standards disallow nested loop emulation like that.

To deal with nested loops, pull the inner loop out into a separate function.


Exercises

  1. What is nested-loop emulation, and why shouldn't you use it? Answer