The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

C nested for Loop

Using a for loop within another for loop is said to be nested for loop. In nested for loop one or more statements can be included in the body of the loop. In nested for loop, the number of iterations will be equal to the number of iterations in the outer loop multiplies by the number of iterations in the inner loop.

nested for Loop Syntax

Let us see how neat a syntax of nested for loop is

Syntax
for (initialize counter; test condition; ++ or --)
{
for (initialize counter; test condition; ++ or --)
{
.// inner for loop
}
.// outer for loop
}

nested for loop Flowchart

Nested for loop

C program - nested for loop

The following example program will clearly explain the concept of nested for loop

nestedfor.c
#include <stdio.h>
int main()
{
int a, b;
for(a = 1; a <= 5; a++)
{
for(b = 1; b <= 5; b++)
{
printf("%d ", b);
}
printf("\n");
}
return 0;
}
  • 1 2 3 4 5
  • 1 2 3 4 5
  • 1 2 3 4 5
  • 1 2 3 4 5
  • 1 2 3 4 5

Note:

The variable a and b is initialized to 1 for the first time when the program execution starts in the for loop. The variable a belongs to outer for loop and a variable b belongs to inner for loop. for a = 1, inner for loop will be executed 5 times. Thus, total number of iterations is 25.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report