Print Pascal's Triangle

Print Pascal's triangle up to N rows using a loop and binomial coefficients.

PythonIntermediate
Python
# Program to print Pascal's triangle

rows = int(input("Enter number of rows: "))

for n in range(rows):
    # print leading spaces
    print(" " * (rows - n), end="")
    coef = 1
    for k in range(n + 1):
        print(coef, end=" ")
        coef = coef * (n - k) // (k + 1)
    print()

Output

Enter number of rows: 5
     1 
    1 1 
   1 2 1 
  1 3 3 1 
 1 4 6 4 1 

We compute binomial coefficients iteratively in each row using the relation: coef = coef * (n - k) // (k + 1).