# Floyd’s Triangle in C

Program to display Floyd’s triangle pattern in C language. There are many programming exercises in the C programming language which involve printing a particular pattern in the console. Floyd’s triangle is one of them. It is based on displaying a pattern of half a pyramid of numbers.

Floyd’s triangle is a right angle triangle of an array of natural numbers. In Floyd’s triangle nth row contents n elements.

## C Program For Floyd’s Triangle

``````#include<stdio.h>
int main()
{
int n, i, j, a=1;
printf("Enter the number of rows: ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
printf("%-5d",a++);
printf("\n");
}
return 0;
}``````

Output for different test-cases:-

Enter the number of rows: 5
`12 34 5 67 8 9 1011 12 13 14 15`

Enter the number of rows: 7
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28

Floyd Triangle in C Explanation

To print Floyd’s triangle in C, the nested loop is required. The outer loop represents the row and the inner loop represents the column. The Floyd’s triangle starts with 1 and every nth row contains n elements. So, the outer loop starts with i=1 and iterate n times. The inner loop starts with j=1 and iterates i times.

In this program, the width modifier is used with printf function, and the display is left-justified to the console. Read More:- Output formatting using printf function in C

## Floyd’s triangle in C using recursion

Using recursion we can display Floyd’s triangle. Read more:- Recursion in C

``````#include<stdio.h>
int row=1;
int a = 1;
void printFloyd(int n)
{
if(n<=0) return;

for(int i=1; i<=row; i++)
printf("%-5d",a++);

printf("\n");
row++;
printFloyd(n-1);
}

int main()
{
int n;
printf("Enter number of rows: ");
scanf("%d",&n);
printFloyd(n);
return 0;
}``````

## Reverse Floyd’s triangle in C

Sample of Input/Output:-

Enter number of rows: 5
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

Enter number of rows: 7
28 27 26 25 24 23 22
21 20 19 18 17 16
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

``````#include<stdio.h>
int main()
{
int n, i, j;

printf("Enter number of rows: ");
scanf("%d",&n);

int k = n*(n+1)/2;
for(i=n; i>=0; i--)
{
for(j=1; j<=i; j++)
printf("%-5d",k--);
printf("\n");
}

return 0;
}``````

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Similar Pattern programs in C