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(); }
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
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(); }
11111
2222
333
44
5
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(); }
12345
2345
345
45
5
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(); }
5
44
333
2222
11111
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(); }
1
22
333
4444
55555
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(); }
*****
****
***
**
*
****
***
**
*
0 comments:
Post a Comment