C nested loop

C nested loop

When loop written inside the another loop it is know as Nested loops. so any types of loops can be inside to any other loop. so while loop may be nested inside another for loop or inside do-while loop. let us take example to understand nested loop concept.

Syntax of Nested loop

Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}

Outer_loop and Inner_loop are the validated loops that can be a ‘while’ ,’for’ or ‘do-while’ loop.

/*program to understand nesting in for loop*/
#include<stdio.h>
int main()
{
int i,j;
for(i=0;i<=10;i++)
{
printf("i=%d",i);
for(j=0;j<=8;j++)
{
printf("j=%d",j);
printf("\n");
}
}
return 0;
}

The outer loop iterates 11 time (0 to 10) and for each iteration of the outer loop inner loop iterates 9 time (0 to 9).

Nested while loop

The nested while loop is any type of loop which is defined inside the ‘while’ loop.

while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}

Nested do while loop

The nested do while loop is any type of loop which is defined inside the another do while loop.

do
{
do
{
// inner loop statements.
}while(condition);
// outer loop statements.
}while(condition);