Python Program to print Floyd’s Triangle | PrepInsta

Floyd’s Triangle

 

In this section, we will learn how to print Floyd’s Triangle using Python.

Floyd’s Triangle is a right-angled triangular array made up of natural numbers. It is named after Robert Floyd. It starts from 1 and consecutively selects the next greater number of the sequence.

Total numbers in the triangle of n rows: n*(n+1)/2.

Floyd's Triangle

Algorithm

  • Take number of rows as input
  • Call floydTriangle(n)
floydTriangle(n):
  1. Initialize count variable c with value 0
  2. Traverse i from 1 to n+1 for n rows and do step 3 to step 7 (Outer Loop for each row)
  3. Traverse j from 0 to i and do step 4 to step 5 (Inner Loop for each elements in a particular row)
  4. Increment variable c by 1
  5. print c in same line
  6. End of Inner Loop
  7. print new line character after each inner iteration
  8. End of Outer Loop

Python Code


#function to print floyd’s triangle
def floydTriangle(n):
    #count variable
    c=0
    #outer loop for each row
    for i in range(1,n+1):
        #inner loop for each elements in a particular row
        for j in range(0,i):
            c+=1
            #print space seperated elements in  each row
            print(c, end=” “)
        #prints new line for new row
        print()
            
#input
n=int(input(“Enter the number of rows: “))
#function call
floydTriangle(n)

Output :

Enter the 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