i2tutorials

Nested Loops

Nested Loops

 

A nested loop refers to a loop that is continued within another loop. If the program has to repeat a loop more than once, the nested loop is preferably used.

In nested loops, the inner loop executes until the loop condition fails, and once the condition of the inner loop is failed then it comes out of that loop. Thereby, the outer loop variable changes its initial value making it feasible for the next iteration. This process continues until the condition mentioned in the outer loop goes wrong.

Hence the total number of iterations in the case of nested loops is given by the product of a number of iterations of the inner loop with a number of iterations of the outer loop.

The possible skeletal syntaxes of nested loops are as given below:

 

For nested in for loop:

 

for( ; ;)
{
for( ; ;)
{
Statements of the inner loop;
}
}

 

For nested in while loop:

 

while(condition)
{
for( ; ;)
{
Statements of the inner loop;
}
}

 

For while nested in for loop:

 

for( ; ;)
{
while(condition)
{
Statements of the inner loop;
}
}

 

The nesting of loops concept can be applied in a variety of forms such as while loop within a while, while within do-while etc depending upon the application to be developed.

 

Example program 1:

 

Program to print the following pattern 1

1

2 3

4 5 6

7 8 9 10

 

#include<stdio.h> 
void main()
{
int i,j,n,a=1;
printf("Enter the number of rows:"); 
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",a); 
a++;
}
printf("\n");
}
}

 

Output:

 

Nested Loops

 

 

 

 

Exit mobile version