Nested For Loop in C


1.What is nested for loop in C ?

Ans: A nested loop means a loop statement inside another loop statement. That is why nested loops are also called “loop inside loops“. We can define any number of loops inside another loop.


Simple Explanation :


We can see that the sir is assigning the project among students. The students will work on the project and after completing the project they will go back to the sir. The sir will check the project. If the project made by student is right then sir will give another project.

Nested for loop also works same it will verify the first condition and if the condition is true it will enter the loop and check the condition inside the loop. It will not come to first loop till the condition of the second loop becomes false.


Working of nested for loop :



Syntax  :

#include <stdio.h>  // Include the standard input/output header file.

for ( initialization; condition; increment ) 
{

   for ( initialization; condition; increment ) 
   {
      
      // statement of inside loop
   }

   // statement of outer loop
}


Example:

1. Write a C program to print a square box using star.

#include<stdio.h>
void main ()
{
    int r,c,num=1;
    for(r=0;r<=3;r++)
   {
for(c=0;c<=4;c++)
{
         if (r+c<3 || r+c>3)
{
printf("*");
}
}
    printf("\n");
}
}


Output :



2. Write a C program to print a pyramid using star.

#include<stdio.h>
int main ()
{
  int r,c;
  for (r=0;r<=5;r++)     
  {
for (c=0;c<=5;c++) 
{
if(r+c<5)   
{
    printf(" ");  
else
{
printf("*");  
}
}
for (c=0;c<r;c++)
{
printf("*");
}
printf("\n");
}
}

Output :



3. Write a C program of count down of Happy new year using delay.

#include <stdio.h>

int main() {
  int i,j,countdown = 3;

  while (countdown > 0) 
  {
    printf("%d\n", countdown);
    for(i=0;i<20000;i++)
    {
    for(j=0;j<20000;j++);
    }
    countdown--;
  }

  printf("Happy New Year!!\n");
}

Output :