Node:Nested loops, Next:, Previous:Terminating and speeding loops, Up:Loops



Nested loops

Just as decisions can be nested, so can loops; that is, you can place loops inside other loops. This can be useful, for example, when you are coding multidimensional arrays. (See Arrays.)

The example below prints a square of asterisks by nesting a printf command inside an inner loop, which is itself nested inside an outer loop.

Any kind of loop can be nested. For example, the code below could have been written with while loops instead of for loops:

#include <stdio.h>

#define SIZE 5

int main()
{
  int square_y, square_x;

  printf ("\n");

  for (square_y = 1; square_y <= SIZE; square_y++)
  {
    for (square_x = 1; square_x <= SIZE; square_x++)
    {
      printf("*");
    }
    printf ("\n");
  }

  printf ("\n");
  return 0;
}

The output of the above code looks like this:

*****
*****
*****
*****
*****