Introduction
Writing programs to print different patterns using programming languages is an excellent way to improve coding skills. Numeric patterns are pretty interesting and are very easy to code. The Number triangle is one such numeric pattern that consists of numbers arranged in a way that represents a triangle. In this blog, let us learn how to print the following three number triangles.
You can also read about dynamic array in c,C Static Function
Approach
All numbers in a number triangle have a relation with the number preceding it or following it. We use a for loop to traverse through each row. The given pattern is split into two or more patterns if possible. Each such pattern will need a for loop of its own.
Pattern1
#include<stdio.h>
int main()
{
int n, i, j, k, a=1;
printf("Enter the number of rows\n");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
for(k=n-1; k>=i; k--)
printf(" ");
for(j=0; j<i; j++)
printf(" %02d ", a++);
printf("\n");
}
}
Output:
Enter the number of rows
5
01
02 03
04 05 06
07 08 09 10
11 12 13 14 15
-
The number of rows to be printed is taken as input from the user. A for loop runs n times to keep track of the row it prints.
-
The first for loop is to print the spaces before every starting number in each row.
- The second for loop is to print the number itself. Variable a holds this value and is incremented each time it is printed.
Pattern2
#include<stdio.h>
int main()
{
int n,i,j,m;
printf("Enter the number of rows\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(int k=n-1;k>=i;k--)
printf(" ");
for(j=1;j<=i;j++)
printf("%d",j);
for(m=i-1;m>0;m--)
printf("%d",m);
printf("\n");
}
}
Output:
Enter the number of rows
5
1
121
12321
1234321
123454321
The main for loop runs to print each row. The given pattern is split as follows:
-
The first inner for loop is to print the spaces before every starting number in each row (section 1).
-
The second inner for loop is to print section 2.
- The third inner for loop is to print section 3.
Pattern3
#include<stdio.h>
int main()
{
int n,i,j,m,a;
printf("Enter the number of rows\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(int k=n-1;k>=i;k--)
printf(" ");
a=i;
for(j=0;j<i;j++)
printf("%d",a++);
a--;
for(m=i-1;m>0;m--)
printf("%d",--a);
printf("\n");
}
}
Output:
Enter the number of rows
5
1
232
34543
4567654
567898765
The main for loop runs to print each row. The given pattern is split as follows:
-
The first inner for loop is to print the spaces before every starting number in each row (section 1).
-
The second inner for loop is to print section 2.
- The third inner for loop is to print section 3.
You can practice by yourself on Online C editor for good understanding.