Nesting of Looping Statements in C

Nesting loops means placing one loop inside the body of another loop. Any variant of loop can be nested inside any other variant of loop just like any variant of if-statement can be nested inside any other variant of if-statement. Also, logically there is not limit on the level of nesting. However, to make code readable and easily understood, proper indentation should be done. While all types of loops may be nested, the most commonly nested loops are for loops. So, let us consider a for loop for explanation of nested loops.

The general syntax of nested loops is as follows

for ( ; condition1 ; ) /* Outer Loop */
{
statement1;
for ( ; conditionA ; ) /* Inner Loop */
{
statementA;
}
statement2;
}

It is obvious from the syntax that during the first iteration of the outer loop, the inner loop gets trigger and executes to completion. Then, during the second iteration of the outer loop, the inner loop is again trigger and executed to its completion. This repeats until the outer loop finishes. This means the outer loop changes only after the inner loop is completely finished and the outer loop takes control of the number of complete executions of the inner loop. The program 1 explains the concept. In this program, the outer loop is executed 5 times while during every iteration of outer loop, the inner loop is also executed 3 times. This means, in total the inner loop will be executed 15 times.

#include <stdio.h>
void main()
{
int i, j;
for (i=1; i<=5; i++)
{
printf(“I will be displayed 5
times\n”);
for (j=1; j <=3; j++)
{
printf(“I will be displayed
15 times\n”);
}
}
}

Program 1: Program to show working of nested loops

Screenshot from 2020-07-20 02-30-10