Nesting Loop

Back - C Language Notes By Vivek Sir email: vivekdubey22@gmail.com (w) 9826424484

·        A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required.

·        Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times.

·        Then, the total number of times the inner loop runs during the program execution is n*m.

Types of nested loops

·        Nested while loop

·        Nested do-while loop

·        Nested for loop

Syntax
 
while (condition1)
{
    statement(s);
    while (condition2)
    {
        statement(s);
        ... ... ...
    }
    ... ... ...
}

 

 
Nested while loop

    i=1;
    while (i <= 5)
    {
        j=1;
        while (j <= i )
        {
            printf("%d ",j);
            j = j + 1;
        }
        printf("\n");
        i = I + 1;
    }

 

 
flowchart of nested while loop in c programming


 

Syntax

do
{
    statement(s);
    do
    {
        statement(s);
        ... ... ...
    }while (condition2);
    ... ... ...
}while (condition1);

 

 
Nested do-while loop

Example

    i=1;
    do
    {
        j=1;
        do
        {
            printf("*");
j = j + 1;
        }while(j <= i);
        i = I + 1;
        printf("\n");
    }while(i <= 5);

 

 
flowchart of nested do while loop in c programming

for (initialization; condition; increment/decrement)
{
    statement(s);
    for (initialization; condition; increment/decrement)
    {
        statement(s);
        ... ... ...
    }
    ... ... ...
}

 

 
Nested for loop

for( i=1;i<=5;i=i+1)

                {

                for (j=1;j<=5;J=j+1)

                                printf(“*”);

                }

printf(“\n”);

 
flowchart of nested for loop in c programming

Back - C Language Notes By Vivek Sir email: vivekdubey22@gmail.com (w) 9826424484