In this post we will learn to print various types of number pyramid using C.
1) Half pyramid of numbers:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
C Program
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows : ");
scanf("%d",&rows);
for(i = 1; i<=rows; i++)
{
for(j = 1; j<= i; j++)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
2) Full pyramid of numbers (type 1):
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
C program
#include <stdio.h>
int main()
{
int i, j = 0, space, rows, k = 0, count = 0;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for(i = 1; i <= rows; i++)
{
for(space = 1;space <= rows-i; space++)
{
printf(" ");
count++;
}
while(j != 2*i - 1){
if(count <= rows -1)
{
printf("%d", i + j);
count++;
}
else{
k++;
printf("%d", (i + j -2 * k));
}
j++;
}
k = count = j = 0;
printf("\n");
}
return 0;
}
3) Full pyramid of numbers (type 2):
1
2 3
4 5 6
7 8 9 10
C Program
#include <stdio.h>
void main()
{
int i,j,space,rows,k,t=1;
printf("Input number of rows : ");
scanf("%d",&rows);
space=rows+4-1;
for(i=1;i<=rows;i++)
{
for(k=space;k>=1;k--)
{
printf(" ");
}
for(j=1;j<=i;j++)
printf("%d ",t++);
printf("\n");
space--;
}
}
4) Pascal's Triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
C Program:
#include <stdio.h>
int main() {
int rows, coefficient = 1, space, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
for (space = 1; space <= rows - i; space++)
printf(" ");
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coefficient = 1;
else
coefficient = coefficient * (i - j + 1) / j;
printf("%4d", coefficient);
}
printf("\n");
}
return 0;
}
5) Floyd's Triangle:
1
2 3
4 5 6
7 8 9 10
C Program:
#include <stdio.h>
int main() {
int rows, i, j, number = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Follow Programmers Door for more.
Comments