To run a loop inside another loop is termed as nested loop. These nested loops are basically used to build two dimensional structures such as building half and full pyramid patterns.
for(…){
for(…){
print(something);
}
}
These loops are built up in two looping:
The first is inner looping and the second is outer looping.
Inner loop will take care of the stars, or any kind of pattern and the outer loop will skip to the next line.
Let us see an example:
The task is to build up a half pyramid * pattern. How to do it?
Code:
#include<stdio.h> int main() { int n; //reads the number printf("Enter the number of rows: "); //asking the user input scanf("%d",&n); //inputting the number of rows for(int i= 0; i<n; i++){ //outer loop which is going to take care of your structure and break after every line for(int j = 0; j<=i; j++){ //inner loop takes care of the stars, or whatever pattern it is.. printf("*"); //star pattern } printf("\n") // break after every line after checking the looping condition } }
//dry run
Value of i | Value of j | Stars |
i=1 i=2 i=3 i=4 | j = 1 j = 1, j = 2(coz j<=i) j = 3, j =1,2,3 j=4, j=1, j=2, j=3, j=4 | * * * * * * * * * * |
Output:
How to invert the pattern?
Code:
#include<stdio.h> int main() { int n; //reads the number printf("Enter the number of rows: "); scanf("%d",&n); for(int i= n; i>=1; i--){ /outer loop runs from n to 1 that is why we are decrementing the value of i for(int j = 1; j<=i; j++){ //inner loop will take care of the pattern generation printf("*"); } printf("\n"); //break after every line after checking the looping condition } }
//dry run
Value of i | Value of j | Stars |
i=5 i=4 i=3 i=2 i=1 | j = 5 j = 1, j = 2, j=3,j=4(coz j<=i) j = 3, j =1,2,3 j=1, j=2 j=1 | * * * * * * * * * * * * * * * |