A loop inside another loop is called a nested loop. You can define any number of loop inside another loop. You can also have any number of nesting level. You can put any type of loop in another type.
In programming there exists situations where you need to iterate single or a set of repetitive statement for a number of times.Such situations in C programming are handled using nested loops.C programming language supports nesting of one loop inside another.
Nested while loop
A while loop inside another while loop is called nested while loop.
Syntax of nested loop
outer_loop
{
inner_loop
{
// Inner loop statement/s
}
// Outer loop statement/s
}
outer_loop and inner_loop is one of the valid C loop.
Syntax of Nested while loop
while (condition1)
{
statement(s);
while (condition2)
{
statement(s);
... ... ...
}
... ... ...
}
Flowchart of Nested while loop
Nested do-while loop
A do-while loop inside another do-while loop is called nested do-while loop.
Syntax of Nested do-while loop
do
{
statement(s);
do
{
statement(s);
... ... ...
}while (condition2);
... ... ...
}while (condition1);
Flowchart of Nested do-while loop
Nested for loop
A for loop inside another for loop is called nested for loop.
Syntax of Nested for loop
for (initialization; condition; increment/decrement)
{
statement(s);
for (initialization; condition; increment/decrement)
{
statement(s);
... ... ...
}
... ... ...
}
Flowchart of Nested for loop