VOOZH about

URL: https://www.geeksforgeeks.org/c/nested-loops-in-c-with-examples/

⇱ Nested Loops in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Nested Loops in C

Last Updated : 7 Nov, 2025

A nested loop means a loop statement inside another loop statement.

  • For a nested loop, the inner loop performs all of its iterations for each iteration of the outer loop.
  • If the outer loop is running from i = 1 to 5 and the inner loop is running from j = 0 to 3. Then, for each value of the outer loop variable (i), the inner loop will run from j = 0 to 3.

1. Nested for Loops

Nested for loop refers to any type of loop that is defined inside a 'for' loop.


Output
i = 0: 0 1 2 3 4 
i = 1: 5 6 7 8 9 
i = 2: 10 11 12 13 14 
i = 3: 15 16 17 18 19 

Below is the equivalent flow diagram for nested 'for' loops:

👁 Nested-for-Loop


2. Nested while Loops

A nested while loop refers to any type of loop that is defined inside a 'while' loop.


Output
Pattern Printing using Nested While loop
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Below is the equivalent flow diagram for nested 'while' loops:

👁 Nested-while-Loop


3. Nested do-while Loops

A nested do-while loop refers to any type of loop that is defined inside a do-while loop.


Output
1 2 3 
1 2 3 

Below is the equivalent flow diagram for nested 'do-while' loops:

👁 Nested-do-while-Loop

4. Hybrid Nested Loops

A hybrid loop structure is where any type of loop is nested inside another loop type.


Output
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2

Break Inside Nested Loops

Whenever we use a break statement inside the nested loops it breaks the innermost loop only and program control goes to the outer loop. Breaking the inner loop does not affects the outer loops.


Output
* * * 
* * * 
* * * 

* * * 

In the above program, the first loop will iterate from 0 to 5 but here if i will be equal to 3 it will break and will not print the * as shown in the output. 

Continue Inside Nested Loops

Whenever we use a continue statement inside the nested loops it skips the iteration of the innermost loop only. The outer loop remains unaffected.


Output
0 1 
0 1 

In the above program, the inner loop will be skipped when j will be equal to 2. The outer loop will remain unaffected.

Uses of Nested Loops

  • Printing Patterns: Nested loops are often used to print complex patterns such as printing shapes, grids, or tables.
  • Searching and Sorting: Nested loops are used in algorithms that involve searching for or sorting elements like bubble sort, insertion sort, matrix searching etc.
  • Multi-Dimensional Data: Nested loops are useful when dealing with multidimensional data structures like 2D or 3D arrays, matrices, list of lists.
  • Dynamic Programming: Nested loops are commonly used in dynamic Programming for solving problems like knapsack problem or longest common subsequence.
Comment
Article Tags: