Nested Loop in C

Introduction

A nested loop in C means using a loop inside another loop. We have three types of loops within C i.e. While Loop, Do While Loop and For Loop. There are a few special cases where we need to have a nested loop. The most common example is printing a pattern.

Example

See this example to make it clear.

#include<stdio.h>

int main()

{

            int i,j;

            for(i=10;i<=13;i++)

            {

                        printf("\nTable of %d:",i);

                        for(j=1;j<=10;j++)

                        {

                                    printf("\n%d * %d = %d",i,j,i*j);

                        }

            }

            return 0;

}

 

Output

Nested Loop in C

Explanation

The above code declares two variables, ‘i’ and ‘j’, as an iterator. ‘i’ is initialized with ‘10’. When ‘i’ is 10, the condition ‘i<=13’ comes out to be true. Thus, the statements inside this loop get executed. The next statement is ‘for(j=1;j<=10;j++)’. So, executing this statement results in:

‘j’ is 1 and 10*1=10 will be printed. Now, the second iteration of the inner loop will take place. ‘i’ is still 10, but ‘j’ is updated to 2. So, 10*2=20 will be printed.

Coming to the last iteration of the inner loop, ‘i’ is still 12, and ‘j’ will be 10 so, 10*10=100 will be printed. Now this time, ‘j’ will be increased by 1 and updated to 11, which doesn’t satisfy ‘j<=10’. Therefore, this will terminate the loop.

Now, coming out of the inner loop, there is no statement after the inner loop. So, ‘i’ in the outer loop will be increased to 11 ( i++) for the next iteration of the outer loop, and ‘Table of 11’ will be printed, and the statement will repeat with different values of ‘j’ from 1 to 10. Again when ‘j’ is updated to 11, the inner loop terminates, and the control will come to the outer loop. In this, the tables of 12 and 13 also get printed.

So, with this nesting, we wrote a minimal program but could print a huge output.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.