- Write a C program to print Floyd's triangle using loop and recursion.

A Floyd’s triangle is a right angled triangle of natural numbers, such that N^{th} row of triangle contains N consecutive numbers from left to right.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

This program print's Floyd's triangle till N^{th} rows.

## C program to print Floyd's triangle using for loop

/* * C program to print Floyd's triangle */ #include<stdio.h> #include<conio.h> int main() { int i, j, rows, counter; printf("Enter the number of rows of Floyd's triangle\n"); scanf("%d", &rows); /* Print Floyd's triangle */ for (counter = 1, i = 1; i <= rows; i++) { /* Print ith row */ for (j = 1; j <= i; j++) { printf("%3d", counter++); } printf("\n"); } getch(); return 0; }

**Program Output**

Enter the number of rows of Floyd's triangle 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

## C program to print Floyd's triangle using recursion

This program uses a user defined recursive function "printFloydTriangle", that takes current row(rowNumber) and total number of rows(totalRows) as input from user and prints current row of triangle and then recursively calls itself to print next row.

As we know that, N^{th} row of triangle contains N number, and all elements of triangle are consecutive natural numbers starting from 1. We can determine the first number of N^{th}row by following expression.

= 1 + 2 + 3 +....+ N =

- No of elements in 1
^{st}row = 1 - No of elements in 2
^{nd}row = 2 - No of elements in 3
^{rd}row = 3 - No of elements in N
^{st}row = N

^{th}row = Sum of number of element in all previous rows(from row 1 to N)= 1 + 2 + 3 +....+ N =

**((N+1)*N)/2 + 1**/* * C program to print Floyd's triangle using recursion */ #include<stdio.h> #include<conio.h> void printFloydTriangle(int rowNumber, int totalRows); int main() { int rows; printf("Enter the number of rows of Floyd's triangle\n"); scanf("%d", &rows); printf("\n"); printFloydTriangle(1, rows); getch(); return 0; } void printFloydTriangle(int rowNumber, int totalRows) { int elementCount, counter; /* Recursion termination condition */ if(rowNumber > totalRows) return; elementCount = ((rowNumber-1)*rowNumber)/2; for (counter = 1; counter <= rowNumber; counter++) { printf("%d ", ++elementCount); } printf("\n"); printFloydTriangle(rowNumber+1, totalRows); }

**Program Output**

Enter the number of rows of Floyd's triangle 4 1 2 3 4 5 6 7 8 9 10

**Related Topics**