Tutorials
Examples
Tests

# C Program to Print Floyd's Triangle

In this article, you will learn and get code about printing of Floyd's triangle in C language. But before going through program, let's first understand about Floyd's Triangle.

### What is Floyd's Triangle

Floyd's triangle is a right-angled triangle created using natural numbers as shown here:

```1
2 3
4 5 6
7 8 9 10
11 12 13 14 15```

may continue upto any number of rows. Here Floyd's triangle is shown upto 5 rows only.

## Print Floyd's Triangle in C

Now let's create a program to print Floyd's triangle with 5 lines or rows:

```#include<stdio.h>
#include<conio.h>
int main()
{
int i, j, num=1;
for(i=0; i<5; i++)
{
for(j=0; j<=i; j++)
{
printf("%d ", num);
num++;
}
printf("\n");
}
getch();
return 0;
}```

This program was build and run under Code::Blocks IDE. Here is its sample run:

The dry run of above program goes like:

• Initially num=1
• Inside the first (outer) for loop, 0 is initialized to i and checks whether it is less than 5 or not
• The condition evaluates to be true. Therefore program flow goes inside the loop
• Now inside the second for loop, 0 is initialized to j and checks whether it is less than or equal to the value of i (0) or not
• The condition evaluates to be true. Therefore program flow goes inside the loop and prints the value of num, that is 1 and then increments its value
• Now num=2
• Program flow goes to the update part of inner for loop and increments the value of j. Now the value of j is 2.
• Program flow goes to condition part, and checks whether the value of j is less than or equal to the value of i or not
• The condition evaluates to be false. Therefore program flow exits from inner for loop
• Prints a new line character. That is, next output's things starts from next line
• Now program flow goes to update part of outer for loop. There, increments the value of i and checks whether it is less than 5 or not
• The condition evaluates to be true again. Therefore program flow again goes inside the loop and executes the inner loop again
• Continue the process until the condition of outer for loop evaluates to be false

### Allow User to Define the Size of Floyd's Triangle

Here is another program that does the same job as of previous one, that is to print Floyd's triangle. But user is allowed to define the size of Floyd's triangle. In other word, program asks from user, that upto how many number of lines, Floyd's triangle expanded.

```#include<stdio.h>
#include<conio.h>
int main()
{
int i, j, num=1, row;
printf("Enter Number of Rows: ");
scanf("%d", &row);
for(i=0; i<row; i++)
{
for(j=0; j<=i; j++)
{
printf("%d ", num);
num++;
}
printf("\n");
}
getch();
return 0;
}```

Here is its sample run, supposing the user input as 10:

#### Same Program in Other Languages

C Online Test

« Previous Program Next Program »