Python Program To Print Floyd’s Triangle

In this tutorial, we will have a look at a similar program to pattern printing which is commonly known by the name Floyd’s triangle in Python. It is undoubtedly a very common program, you might have heard about this at least once.

Floyd’s triangle

A Floyd’s triangle is a consecutive series of natural numbers in a right-angled triangle. This is what Floyd’s triangle looks like-

1
2 3
4 5 6
7 8 9 10

Approach

The way we can approach to this problem could be-

  1. Input n (number of rows).
  2. Initialize count as 1 which will be incremented later.
  3. Use a for loop initialize i from 1 to n+1
  4. Use a nested for loop initialize j from 1 to i+1.
  5. Print count with end=” “.
  6. Increment the value of count by 1.
  7. print() will change the line.

Implementation in Python

As we have discussed approach, now we can implement it using a for loop in Python as shown below-

n = int(input("Enter the total Number of Rows  : "))
count= 1


for i in range(1, n + 1):
    for j in range(1, i + 1):        
        print(count, end = '  ')
        count = count + 1
    print()
Enter the total Number of Rows : 5
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15

So we have printed our expected output. We can also use a similar approach using a while loop. The approach is quite similar with a different syntax as-

n = int(input("Enter the total Number of Rows  : "))
count= 1
i = 1
while(i <= n):
    j = 1
    while(j <= i):        
        print(count, end = '  ')
        count = count + 1
        j = j + 1
    i = i + 1
    print()
Enter the total 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

So we have discussed two methods using for loop and a while loop using the similar approach. I hope you liked this tutorial! Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *