Nested Loops
Nested Loops
A nested loop means a statement inside another loop statement. That is why nested loops are
also called "loop inside loops". We can define any number of loops inside another loop.
Syntax:
Example: Below program uses a nested for loop to print a 3D matrix of 2x3x2.
c
C program to print elements of Three-Dimensional Array
// with the help of nested for loop
#include < stdio.h>
int main ()
return O ;
Output
Element at
Element at
Element at
Element at
Element at
Element at
Element at
Element at
Element at
Element at = 10
Element
Element at = 11
Syntax:
while(condition) {
while(condition) {
int main ( )
int end
int i
while (i end)
printf( " ) ;
int j
while (j i) [
printf( "Ed
return O ;
Output
12
123
1234
12345
3. Nested do-while Loop
A nested do-while loop refers to any type of loop that is defined inside a do-while loop. Below is
the equivalent flow diagram for nested 'do-while' loops:
do while loop in C
Syntax:
do{
do{
Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any
type of loop nested inside any type and to any level.
Syntax:
do{
while(condition) {
Finclude<math.h>
#include < stdio.h>
printf( "Ed
int n 315;
primeFactors(n);
return O ;
Output:
3357
Break Inside Nested Loops
Whenever we use a break statement inside the nested loops it breaks the innermost loop and
program control is inside the outer loop.
Example:
int main ()
int 1
for int O; 14
for int j
// This Inner loop will break when i:-3
if (i 3)
break;
printf(
printf( "\n");
return O ,
Output
In the above program, the first loop will iterate from O to 5 but here if i will be equal to 3 it will
break and will not print the * as shown in the output.
int main ()
int
for (int O; 14
for (int j
// This Inner loop will skip when j=
if (j-
continue
printf( "Ed
printf( "\n");
return O ;
In the above program, the inner loop will be skipped when j will be equal to 2. The outer loop will
remain unaffected.