Javaexercise.com

How To Create Floyd Triangle In Python?

A Floyd triangle is a triangle made of with first natural number. A Floyd triangle looks like the below. In this article, we will learn to create Floyd triangle using Python.

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

Notice from the triangle above that the number of columns in a row is equal to that row's number.

For example, the number for columns in the second row is two, in the third row is 3, and so on.

In the code, we run two nested loops: the outer loop runs each row and the inner loop runs for each column in each row.

The outer loop runs from 1 to n, where n is the number of rows we want in our triangle. The inner loop runs from 0 to the row number. There is a variable called nn, which keeps track of the natural numbers. After each termination of each inner loop, we print the next line.

Algorithm for Floyd triangle in Python

  1. initialize variable n to the number of rows

  2. initialize variable nn to 1

  3. apply for loop from 1 to n using loop variable i

  4. apply nested for loop from 1 to i using loop variable j

  5. print the value of nn

  6. increment nn by 1

Python Code

The code for creating Floyd's triangle is:

n =7
nn = 1
for i in range(1, n + 1):
 
    for j in range(1, i + 1):
         print(nn, end = " ")
         nn += 1
         
    print("")

Output:

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