Create a Python program to print the first n rows of Pascal’s Triangle

Create a Python program to print the first n rows of Pascal’s Triangle, a triangular array where each number is the sum of the two numbers directly above it.

The correct answer and explanation is :

Python Program to Print the First n Rows of Pascal’s Triangle

Explanation:

Pascal’s Triangle is a triangular array of numbers where the first and last elements of each row are 1, and each other element is the sum of the two numbers directly above it in the previous row. The program to generate Pascal’s Triangle involves a few key steps:

  1. Initializing the Triangle: A list named triangle is initialized to store the rows of Pascal’s Triangle.
  2. Row Construction:
  • We loop through each row (i) from 0 to n-1. The number of elements in the i-th row is i + 1 (since the first row has 1 element, the second has 2, etc.).
  • For each row, we first initialize it with 1s. This accounts for the fact that the first and last elements of every row are always 1.
  1. Filling the Middle Values: For any row i (where i > 1), the values in the middle are calculated by adding the two numbers directly above them in the previous row. These values are located at positions j in the row, where 1 <= j <= i - 1.
  2. Appending the Row: After filling in the row, it is appended to the triangle list.
  3. Printing the Triangle: After the triangle is built, we print each row to display the final Pascal’s Triangle.

Example:

For n = 5, the output would be:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

In this example:

  • The first row contains just a 1.
  • The second row has two 1s.
  • The third row has three elements: 1, 2, and 1, where 2 is the sum of the two 1s from the previous row.
  • Similarly, each subsequent row builds upon the previous row by summing adjacent numbers.

This program gives a clear and efficient way to generate and print Pascal’s Triangle for any number of rows, n.

Scroll to Top