In this post, we will learn how to print Floyd’s triangle in Python with a detailed explanation and example, but before we jump into the coding part, let’s first understand what Floyd’s triangle is.

What is Floyd’s Triangle?

Floyd’s Triangle is a right-angled triangular array of natural numbers. It is named after Robert W. Floyd. The triangle is constructed in such a way that the first row contains one element, the second row contains two elements, the third row contains three elements, and so on.

The numbers are sequentially arranged starting from 1 in the top left corner and increasing by 1 with each new element.

Algorithm

  1. Ask the user to enter the number of rows (n).
  2. Set a variable called num to 1.
  3. Use a nested for loop:
    a. The outer loop iterates from 1 to n (inclusive) to represent each row.
    b. The inner loop iterates from 1 to the current row number (inclusive).
  4. Inside the nested loop:
    a. Print the value of num.
    b. Increment num by 1.
  5. After the inner loop, print a newline character to move to the next row.

Now we know what Floyd’s triangle is and how we will implement it using Python, but before we jump into the program part, there are a few programming concepts you must know:

  1. How to take input from the user &
  2. For-loop

Source Code

n = int(input("Enter a number of rows: "))
num = 1
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(num, end=' ')
        num += 1
    print()

Output

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

We will also modify the above program and rewrite it using a Python function. Let’s see how.

Floyd’s Triangle in Python Using Function

def floyds_triangle(n):
    num = 1
    for i in range(1, n + 1):
        for j in range(1, i + 1):
            print(num, end=' ')
            num += 1
        print()

# Example usage
n = int(input("Enter a number of rows: "))
floyds_triangle(n)

Output

Enter a number of rows: 4
1
2 3
4 5 6
7 8 9 10

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment