Nested Loops in C

For Complete YouTube Video: Click Here

In this class, we will try to understand Nested Loops in C.

We have already discussed while, do-while and, for loops.

Nested Loops

Nested loops are the use of a loop in another loop.

Nested loops are very frequently used in programming practices.

Though the definition looks very simple, nested loops will have a greater impact on the output.

Nested Loops Examples

We will try to understand the use of nested loops with an example.

The image below is a programming example to understand nested loops.

Nested Loops in C Example
Nested Loops in C Example

The above program prints the given number of multiplication tables by the end-user.

If the user asks for five multiplication tables, the program will print the tables from 1 to 5.

The above program uses a two-level nesting.

We can do the nesting of the loops to any level.

Any loop can be nested in another loop; this means a ‘for loop can be nested in a while loop, or a while loop can be nested in a do-while loop.

The outer for-loop in the program will iterate for n times.

The value of n is the number of tables to be printed.

Every time we enter the outer for loop, the inner for loop will iterate ten times.

Now can you guess how many times the inner loop iterates for a value of n as 5.

The inner loop will iterate 50 times.

Try to think about this concept of iteration until you get the clarity.

The printf(“%d * %d = %d\n”, i, j, (i*j)); function of the inner for loop will print the multiplication table.

Nested Loops Output

The output of the program for the value of n = 5 is shown in the image below.

Nested Loops in C Output
Nested Loops in C Output