C++ Nested Loop

A loop within another loop is called a nested loop. Let's take an example,

Suppose we want to loop through each day of a week for 3 weeks.

To achieve this, we can create a loop to iterate three times (3 weeks). And inside the loop, we can create another loop to iterate 7 times (7 days). This is how we can use nested loops.


Example: Nested for Loop

Output

Week: 1
    Day:1
    Day:2
    Day:3
    ... .. ...
Week: 2
    Day:1
    Day:2
    Day:3
    ... ... ..

We can create nested loops with while and do...while in a similar way.


Example: Displaying a Pattern

Output

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

In this program, the outer loop iterates from 1 to rows.

The inner loop iterates from 1 to columns. Inside the inner loop, we print the character '*'.


break and continue Inside Nested Loops

When we use a break statement inside the inner loop, it terminates the inner loop but not the outer loop. For example,

Example: break Inside Nested Loops

Output

Week: 1
    Day:1
    Day:2
    ... .. ...
Week: 2
Week: 3
    Day:1
    Day:2
    ... .. ...

This program does not run the inner loop when the value of i is 2 i.e. it does not print the days of the 2nd week. The outer loop that prints the weeks is unaffected.


Similarly, when we use a continue statement inside the inner loop, it skips the current iteration of the inner loop only. The outer loop is unaffected. For example,

Example: continue Inside Nested Loops

Output

Week: 1
    Day:2
    Day:4
    Day:6
Week: 2
    Day:2
    Day:4
    Day:6
Week: 3
    Day:2
    Day:4
    Day:6

This program prints only those days that are even.

Whenever the days_in_week is odd, the continue statement skips that iteration of the inner loop.