Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python Program to print Pascal’s Triangle

Pascal’s Triangle

 

Pascal’s triangle  is a triangular array of Binomial Coefficients. It is named after the French Mathematician Blaise Pascal.

Each number in the row is the sum of the left and the right number on the above row. If a number is missing in the row then it is assumed to be 0.The first row starts with 1.

Pascal’s Triangle

Algorithm

  • Number of rows is taken as input from user
  • Call function pascalTriangle(n)
pascalTriangle(row):
  1. Traverse i from 0 to row and do Step 2 to Step 10(Outer Loop for each row)
  2. Initialize a coefficient variable c with value 1
  3. Traverse j from 1 to row-i and do Step 4  (1st Inner loop to print space in a particular row)
  4. print blank space ” “.
  5. End of 1st Inner Loop to print blank space
  6. Traverse k from 0 to i+1 and do Step 7 to Step 8 (2nd Inner loop to print number elements in a particular row)
  7. print space separated elements in each row
  8. Calculate c=c*(i-k)//(k+1)
  9. End of 2nd Inner Loop to print number elements
  10. Print new line character after each inner iteration
  11. End of Outer Loop

Python Code:

#function to print pascal’s triangle
def pascalTriangle(row):
    #outer loop for each row
    for i in range(0,row):
        #coeff variable
        c=1
        #inner loop to print space in the row
        for j in range(1,row-i):
            #print blank space
            print(”  “,end=” “)
        #inner loop to print number elemts in a particular row
        for k in range(0,i+1):
            #print space seperated elements in  each row
            print(”  “,c,end=” “)
            #calculate c
            c=c*(i-k)//(k+1)
        #prints new line for new row
        print()

#input
n=int(input(“Enter the number of rows: “))
#function call
pascalTriangle(n)
Output :

Enter the number of rows: 7

                     1 
                  1     1 
               1     2     1 
            1     3     3     1 
         1     4     6     4     1 
      1     5     10    10    5     1 
   1     6     15    20    15    6     1