Python program to print Floyd’s Triangle (3 Ways)

In this program, we will learn how to print Floyd’s Triangle using the Python programming language.

What is Floyd’s Triangle?

It is a right-angled triangular array of natural numbers which is named after Robert Floyd.

We discuss three ways to write code for it.

  • Using for Loop
  • Using while Loop
  • Using Recursion

Python programming code to print Floyd’s Triangle

Using for Loop

Code:-

rows = int(input("Enter the Number of Rows: "))
num = 1

print("Floyd's Triangle") 
for i in range(1, rows + 1):
    for j in range(1, i + 1):        
        print(num, end = ' ')
        num = num + 1
    print()

Using while Loop

Code:-

rows = int(input("Enter the Number of Rows: "))

num = 1
i = 1
print("Floyd's Triangle")
while(i <= rows):
    j = 1
    while(j <= i):        
        print(num, end = ' ')
        num = num + 1
        j = j + 1
    i = i + 1
    print()

Using Recursion

Code:-

def printFloydTriangle(rows):   
    if(rows <= 0):
        return

    for i in range(1, printFloydTriangle.col+1):
        print(printFloydTriangle.num, end=" ")
        printFloydTriangle.num += 1
        
    print()
    printFloydTriangle.col += 1
    rows -= 1
    printFloydTriangle(rows) 

printFloydTriangle.col = 1
printFloydTriangle.num = 1
rows = int(input("Enter the Number of Rows: "))

print("Floyd's Triangle") 
printFloydTriangle(rows)

Output:-

Enter the Number of Rows: 5
Floyd’s Triangle
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

You can learn about many other Python Programs Here.

Best Books for learning Python with Data Structure, Algorithms, Machine learning and Data Science.

The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...