Related Tags

Printing patterns with numbers using nested for-loops

Overview

We will look into some of the printing patterns given below.

• Nested-Loops help to solve printing pattern problems.
• We basically have an outer-loop nested within an inner-loop.

Syntax of nested-for loop

for(initialization;condition;updation)
{
for(initialization;condition;updation)
{
// inner-loop staments
}
// outer-loop statements
}


Explanation

• 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.

Pattern-1

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");
}
}

Pattern-2

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");
}
}

Pattern-3

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");
}
}

Pattern-4

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");
}
}

Pattern-5

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");
}
}

Pattern-6

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 %2operation 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");
}
}

Pattern-7

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");
}
}

Pattern-8

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");
}
}


Pattern-9

• 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");
}
}

Pattern 10

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

RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time