Tutorialspoint
Problem
Solution
Submissions

Pascal’s Triangle

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 10

Write a C++ program to print Pascal's triangle up to the given number of rows n.

Example 1
  • Input: n = 5
  • Output:
    1
    1 1
    1 2 1
    1 3 3 1
    1 4 6 4 1
  • Explanation:
    • Step 1: First row of Pascal's triangle is always [1].
    • Step 2: For subsequent rows, each element is the sum of the two elements above it.
    • Step 3: For row 2, we get [1, 1].
    • Step 4: For row 3, we calculate [1, 1+1, 1] = [1, 2, 1].
    • Step 5: For row 4, we calculate [1, 1+2, 2+1, 1] = [1, 3, 3, 1].
    • Step 6: For row 5, we calculate [1, 1+3, 3+3, 3+1, 1] = [1, 4, 6, 4, 1].
    • Step 7: Print all rows up to n = 5.
Example 2
  • Input: n = 3
  • Output:
    1
    1 1
    1 2 1
  • Explanation:
    • Step 1: First row of Pascal's triangle is always [1].
    • Step 2: For subsequent rows, each element is the sum of the two elements above it.
    • Step 3: For row 2, we get [1, 1].
    • Step 4: For row 3, we calculate [1, 1+1, 1] = [1, 2, 1].
    • Step 5: Print all rows up to n = 3.
Constraints
  • 1 ≤ n ≤ 20
  • Time Complexity: O(n²)
  • Space Complexity: O(n²)
NumberControl StructuresGoogleGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use nested loops to compute each element based on combinations.
  • Each element in a row can be derived from the previous element.

Steps to solve by this approach:

 Step 1: Create a 2D array to store the triangle values.

 Step 2: Iterate through each row from 0 to n-1.
 Step 3: For each row, iterate through columns from 0 to the current row number.
 Step 4: Set edge values (first and last in each row) to 1.
 Step 5: Calculate middle values as the sum of two numbers from the previous row.
 Step 6: Print each value in the current row followed by a space.
 Step 7: Move to a new line after each row is printed.

Submitted Code :