Print Pascal's Triangle

Print Pascal's Triangle

Hard C++ Pattern Printing 45 views
Explanation Complexity

Problem Statement

Print Pascal's triangle with numbers.
Real Life: Important mathematical triangle in combinatorics.

Input Format

An integer n (number of rows).

Output Format

Pascal’s Triangle printed up to n rows.

Example

5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Constraints

• n ≥ 1

• Use integers

• Use loops only

Concept Explanation

Pascal’s Triangle is a number pattern where:

• First and last number of every row is 1.

• Middle numbers are the sum of two numbers just above it.

It is widely used in combinations and probability.

Step-by-Step Explanation

1.Take input n.

2.Print rows from 0 to n-1.

3.For each row i:

• First and last value is 1.

4.For middle positions j:

• Value = previous row j-1 + previous row j.

• Formula:
C[i][j] = C[i-1][j-1] + C[i-1][j]

5.Print each row on a new line.

Concept Explanation

Pascal’s Triangle is a number pattern where:

• First and last number of every row is 1.

• Middle numbers are the sum of two numbers just above it.

It is widely used in combinations and probability.

Step-by-Step Explanation

1.Take input n.

2.Print rows from 0 to n-1.

3.For each row i:

• First and last value is 1.

4.For middle positions j:

• Value = previous row j-1 + previous row j.

• Formula:
C[i][j] = C[i-1][j-1] + C[i-1][j]

5.Print each row on a new line.

Input / Output Format

Input Format
An integer n (number of rows).
Output Format
Pascal’s Triangle printed up to n rows.
Constraints
• n ≥ 1

• Use integers

• Use loops only

Examples

Input:
5
Output:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

Example Solution (Public)

C++
void pattern_q12_pascals_triangle() {
    int n = 5;
    
    for(int i = 0; i < n; i++) {
        // Print spaces for alignment
        for(int j = 0; j < n - i - 1; j++) {
            cout << " ";
        }
        
        int value = 1;
        for(int j = 0; j <= i; j++) {
            cout << value << " ";
            value = value * (i - j) / (j + 1);
        }
        cout << endl;
    }
}

Official Solution Code

void pattern_q12_pascals_triangle() {
    int n = 5;
    
    for(int i = 0; i < n; i++) {
        // Print spaces for alignment
        for(int j = 0; j < n - i - 1; j++) {
            cout << " ";
        }
        
        int value = 1;
        for(int j = 0; j <= i; j++) {
            cout << value << " ";
            value = value * (i - j) / (j + 1);
        }
        cout << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.