We will look into some of the printing patterns given below.
outer-loop
nested within an inner-loop
.for(initialization;condition;updation)
{
for(initialization;condition;updation)
{
// inner-loop staments
}
// outer-loop statements
}
- To work with these patterns it is important to understand the looping variable condition applied to it.
- We consider the outer loop for running it the necessary number of times, and the inner loop is used to print the pattern.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include <stdio.h> int main() { for(int i=1;i<=5;i++) { for(int j=1;j<=i;j++) { printf("%d ",j); } printf("\n"); } }
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include <stdio.h> int main() { for(int i=1;i<=5;i++) { for(int j=1;j<=i;j++) { printf("%d ",i); } printf("\n"); } }
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
#include <stdio.h> int main() { for(int i=5;i>=1;i--) { for(int j=1;j<=i;j++) { printf("%d ",j); } printf("\n"); } }
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
#include <stdio.h> int main() { for(int i=1;i<=5;i++) { for(int j=i;j<=5;j++) { printf("%d ",j); } printf("\n"); } }
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
#include <stdio.h> int main() { for(int i=5;i>=1;i--) { for(int j=5;j>=i;j--) { printf("%d ",j); } printf("\n"); } }
1
1 0
1 0 1
1 0 1 0
1 0 1 0 1
- This pattern is simply an extension of Pattern-1.
- This pattern is obtained by performing
%2
operation on each element.
#include <stdio.h> int main() { for(int i=1;i<=5;i++) { for(int j=1;j<=i;j++) { printf("%d ",j%2); } printf("\n"); } }
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
#include<stdio.h> int main() { int i,j,k=1; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf("%d ",k++); } printf("\n"); } }
1
0 1
0 1 0
1 0 1 0
1 0 1 0 1
- We can get this pattern by performing
%2
operation on Pattern-7.
#include<stdio.h> int main() { int i,j,k=1; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) { printf("%d ",(k++)%2); } printf("\n"); } }
- Now, we will add the required number of spaces in a given pattern.
- We will be adding another loop for adding the required number of spaces.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include <stdio.h> int main() { int i,j,k; for(i=1;i<=5;i++) { for(k=5;k>=i;k--) { printf(" "); } for(j=1;j<=i;j++) { printf("%d",j); } printf("\n"); } }
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
- We can get this pattern by adding a
space
to Pattern-9.
#include <stdio.h> int main() { int i,j,k; for(i=1;i<=5;i++) { for(k=5;k>=i;k--) { printf(" "); } for(j=1;j<=i;j++) { printf("%d ",j); } printf("\n"); } }
RELATED TAGS
CONTRIBUTOR
View all Courses