Nested Looping

C languages allows us to create a loop inside another loop.

Example

Print 5 * 5 box like below,

nested loop example 5 * 5 box

Here, we should use two loops.

Inner loop will print 5 stars. Like *****

Outer loop will execute inner loop 5 times.




Syntax


//nested while loop
while(condition)
{
    while(condition)
    {
         //statements
    }
}

//nested do..while
do
{
    do
    {
         //statements
    }while(condition);
 
}while(condition);

//nested for loop
for(init; condition; inc or dec)
{
    for(init; condition; inc or dec)
    {
         //statements
    } 
}




Program

Write a program to print 5 * 5 box.


Example

#include<stdio.h>

int main()
{
    int i,j;
 
    for(i=1;i<=5;i++) //it will execute inner loop 5 times
    {
         for(j=1;j<=5;j++) //it will print 5 stars continously
         {
             printf("*");
         }
         printf("\n"); //It will give a newline, once 5 stars are printed.
    }
 
    return 0;
}


Topics You Might Like