C Nested Loops
C language allows using one loop inside another loop. The following examples illustrate this concept.
Syntax
In C languageNested for loopSyntax of the statement:
for (initialization; condition; increment/decrement)
{
statement(s);
for (initialization; condition; increment/decrement)
{
statement(s);
... ... ...
}
... ... ...
}
Flowchart:
In C languageNested while loopSyntax of the statement:
while (condition1)
{
statement(s);
while (condition2)
{
statement(s);
... ... ...
}
... ... ...
}
Flowchart:
In C languageNested do...while loopSyntax of the statement:
do
{
statement(s);
do
{
statement(s);
... ... ...
}while (condition2);
... ... ...
}while (condition1);
Flowchart:
One thing worth noting about nested loops is that you can nest any type of loop inside any other type of loop. For example, a for loop can be nested inside a while loop, and vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100:
Nested for example
When the above code is compiled and executed, it produces the following results:
2 是质数 3 是质数 5 是质数 7 是质数 11 是质数 13 是质数 17 是质数 19 是质数 23 是质数 29 是质数 31 是质数 37 是质数 41 是质数 43 是质数 47 是质数 53 是质数 59 是质数 61 是质数 67 是质数 71 是质数 73 是质数 79 是质数 83 是质数 89 是质数 97 是质数
Nested while example
When the above code is compiled and executed, it produces the following results:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Nested do-while example
When the above code is compiled and executed, it produces the following results:
* ** *** **** *****other extensions