Table of Contents
A nested loop is a loop placed inside another loop. The inner loop completes its iterations for each iteration of the outer loop.
#include <stdio.h>
int main()
{
int i, j;
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 2; j++)
{
printf("i = %d, j = %d\n", i, j);
}
}
return 0;
}
Example Output #
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
Explanation #
The outer loop controls i:
for (i = 1; i <= 3; i++)
For each value of i, the inner loop runs completely:
for (j = 1; j <= 2; j++)
When i is 1, the inner loop runs with j equal to 1 and 2. The same process occurs for i values 2 and 3.
Therefore, the inner loop executes 2 times for each of the 3 outer-loop iterations, resulting in a total of 6 executions of the printf() statement.