WHAT'S NEW?
Loading...

Nested Loop in C Programming

When the body part of the loop contains another loop then the inner loop is said to be nested within the outer loop. Since a loop may contain other loops within its body, there is no limit of the number of loops that can be nested. in the case of nested loop, for each value or pass of outer loop, inner loop is completely executed. Thus, inner loop operates/moves fast and outer loop operates slowly. For example we can write syntax of nested for loop as.
    for(initialization; condition; increment/decrement){
          for(initialization; condition; increment/decrement){
                statement (s); 
          }
    } 

Example 1: 

#include<stdio.h>
void main(){
 int i, j; 
 for(i=1; i<=3; i++){
  printf("Outer loop %d \n",i); 
  for(j=1; j<=4; j++){
   printf("This is inner loop %d \n",j); 
  }
 }
 getch(); 
}
Output
Outer loop 1
This is inner loop 1
This is inner loop 2
This is inner loop 3
This is inner loop 4
Outer loop 2
This is inner loop 1
This is inner loop 2
This is inner loop 3
This is inner loop 4
Outer loop 3
This is inner loop 1
This is inner loop 2
This is inner loop 3
This is inner loop 4

In the above program firs it execute the outer loop one time and program flow enters into inner loop then inner loop executes 4 times. After executing inner loop, it goes to the next line of statement which is printf("\n"); it gives a new line, after that again it executes the outer loop once again. In this way it executes outer loop 3 times and in every outer loop it executes inner loop 4 times.

Nested loops are also used for printing different types of patterns, Such as:

Example 2:
#include<stdio.h>
void main(){
 int i, j; 
 for(i=1; i<=5; i++){
  for(j=i; j<=5; j++){
   printf("%d",i); 
  }
  printf("\n"); 
 }
 getch(); 
}
Output
11111
2222
333
44
5

Example 3 :
#include<stdio.h>
void main(){
 int i, j; 
 for(i=1; i<=5; i++){
  for(j=i; j<=5; j++){
   printf("%d",j); 
  }
  printf("\n"); 
 }
 getch(); 
}
Output
12345
2345
345
45
5

Example 4 :
#include<stdio.h>
void main(){
 int i, j; 
 for(i=5; i>=1; i--){
  for(j=i; j<=5; j++){
   printf("%d",i); 
  }
  printf("\n"); 
 }
 getch(); 
}
Output
5
44
333
2222
11111

Example 5:
#include<stdio.h>
void main(){
 int i, j; 
 for(i=1; i<=5; i++){
  for(j=i; j>=1; j--){
   printf("%d",i); 
  }
  printf("\n"); 
 }
 getch(); 
}
Output
1
22
333
4444
55555

Example 6:
#include<stdio.h>
void main(){
 int i, j; 
 for(i=1; i<=10; i++){
  for(j=i; j<=5; j++){
   printf("*"); 
  }
  printf("\n"); 
 }
 getch(); 
}
Output
*****
****
***
**
*

0 comments:

Post a Comment