Nested loop in C programming with examples


To run the particular block of code continuously until a required condition is fulfill is called looping. It is used to perform looping operation. When the condition will become false the execution of loop will be stopped.

A loop inside another loop is called nested loop so one for loop inside another for loop is called nested for loop and so on.

Syntax

From the syntax we can see that there are two for loops are used in which one for loop is inside other. Here i am using only for loop but we can use any loops like for loop, while loop or do while loop inside any loops. for example we can use while loop inside for loop, for loop inside while loop , while loop inside do while loop etc.

Example : Pattern Printing

Pattern program is one of the most useful program which is made using nested loop. Here i am going to print a simple square pattern of 4x4 dimension. Here i am using two for loop to print this pattern. Outer for loop is using for row and inner for loop is using for column. Variable i is used for outer loop or row and variable j is used for inner loop or column.
 
Note: Don't forget to change line after closing brackets of inner loop other all stars will print in a single line.

#include<stdio.h>
int main()
{
//outer loop
for(int i=1;i<=4;i++)
{
  //inner loop
  for(int j=1;j<=4;j++)
  {
  	printf("* ");
  }
  printf("\n");
}
}
/*
### output ###
* * * *
* * * *
* * * *
* * * *
*/

Example :Print all prime numbers between range

This type of program mostly asked in any Viva or interview or exam paper of computer science students that can be made by using nested loop in a very simple way.

#include<stdio.h>
int main()
{
 int n;
 printf("Enter number upto you want to print prime number\n");
 scanf("%d",&n);
 for(int i=2;i<=n;i++)
  {
 	int no=i,m=0;
	for(int j=2;j<=no-1;j++)
     {
	  if(no%j==0)
	  m=1;
     }
	 if(m==0)
	 printf("%d ",no);
  }
}
/*
### Output ###
Enter number upto you want to print prime number
30
2 3 5 7 11 13 17 19 23 29
*/

Here I am requesting if you found this post was helpful for you then let me know by your comment in below comment box and share it with your friend. Also you can contact me on Instagram @rajusunagar_

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

Thank you!!.......

Post a Comment

0 Comments