Nested For Loop

Nested for loop

We already know that what is “for” loop. In this lesson we will discuss that how to use multiple for loops for completing a complex task.

Nesting loops means using a loop inside another.


init : initialization of looping variable

condition : the stopping condition of loop

increment : the factor by which the looping variable will increment.

statements : loop body

Flow Chart:

How does it work?

To understand how nested for works, let’s look at the example below;

The output of this program will be;

It can be seen from the code that;

  • “r” has been used as the looping variable of the outer for loop.
  • “c” has been used as the looping variable for the inner loop.

So, by observing the output, we can conclude that;

  • All the iterations of the inner loop are executed for a single iteration of the outer loop.
  • Then the program returns to the outer loop and evaluates the loop condition, if it turns out true

    • Then the program again enters the inner loop and executes all of its iterations until the looping condition of the inner loop becomes false
  • The cycle continues until the looping condition of the outer loop becomes false.


While nesting any of the programming structures either it be decision control or loops, one must use indentation to make the program readable. The inner loop must be written after indents. The program executes smoothly otherwise, but if any error occurred then it becomes very difficult to debug a less readable program.