Nested loops in C#

Last Updated : 8 Sep, 2025

Nested loops are those loops that are present inside another loop. In C#, you can nest for, while and do-while loops inside each other and any type of loop can be placed within another.

Nested for Loop

In C#, the for loop is used when the number of iterations is known beforehand. Nesting is allowed, meaning you can place one for loop inside another.

Syntax:

for(variable initialization; testing condition; increment / decrement){
for(variable initialization; testing condition; increment / decrement){
// Statements
}
}

Example: 

C#
using System; 

class GFG{
    
public static void Main(){ 
    
    // for loop within another for loop printing GeeksforGeeks 
    for(int i = 0; i < 4; i++) 
        for(int j = 1; j < i; j++) 
            Console.WriteLine("GeeksforGeeks!!"); 
  } 
} 

Output
GeeksforGeeks!!
GeeksforGeeks!!
GeeksforGeeks!!

Nested while Loop

In a while loop, the test condition is given at the beginning of the loop and all statements are executed till the given boolean condition satisfies and when the condition becomes false, the control will be out from the while loop.

Nesting of a while loop is allowed, which means you can use while loop inside another while loop.

Syntax:

while(condition) {
while(condition) {
// Statements
}
// Statements
}

Example:

C#
using System; 

class GFG{
    
public static void Main(){ 
    int x = 1, y = 2;
    
    while (x < 4){
        Console.WriteLine("Outer loop = {0}", x);
        x++;
    
        while (y < 4){
            Console.WriteLine("Inner loop = {0}", y);
            y++;
        }
    }
} 
}

Output
Outer loop = 1
Inner loop = 2
Inner loop = 3
Outer loop = 2
Outer loop = 3

Note: It is not recommended to use nested while loop because it is difficult to maintain and debug.

Nested do-while Loop

In C#, the do-while loop is similar to the while loop with the only difference that is, it checks the condition after executing the statements.

Nesting of a do-while loop is allowed, which means you can use a do-while loop inside another do-while loop.

Syntax:

do
{
// Statements
do
{
// Statements
}
while(condition);
}
while(condition);

Example:

C#
using System; 

class GFG{
    
public static void Main() { 
    int x = 1;
    do{
        Console.WriteLine("Outer loop = {0}", x);
        int y = x;
    
        x++;
                
        do{
            Console.WriteLine("Inner loop: {0}", y);
            y++;
        } while (y < 4);

    } while (x < 4);
} 
}

Output
Outer loop = 1
Inner loop: 1
Inner loop: 2
Inner loop: 3
Outer loop = 2
Inner loop: 2
Inner loop: 3
Outer loop = 3
Inner loop: 3


Comment

Explore