Nested Loops in C
In this article, you will come to know about the nested loops in C programming and the usage of it.
Nested Loops in C
Nesting of loops is a key feature in C, which allows the looping of statements inside another loop. N number of loops can be defined inside another loop, i.e., there is no restriction for defining the number of loops.
A nested loop is a loop statement inside another loop statement. Hence nested loops are also called “loop inside loop’’.
You can also define any type of loop inside another loop; for example, you can define a do….while loop inside for loop. You can use one or more loops inside any other while, for, or do….while loop.
Syntax for Nested For loop
for( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
// statements of inside loop
}
// statements of outer loop
}
Syntax for Nested While loop
while(condition) {
while(condition) {
// statements of inside loop
}
// statements of outer loop
}
Syntax for Nested Do-While loop
do
{
do{
// statements of inside loop
}while(condition);
// statements of outer loop
}while(condition);
Below, let us look at an example of a nested for loop.
Example
#include <stdio.h>
int main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
printf("%d, %d\n",i ,j);
}
}
return 0;
}
Output
0, 0
0, 1
0, 2
1, 0
1, 1
1, 2
As the above example, the other loops like while, do..while can also be nested the same way.