Pascal's Triangle

Program to print Pascal's triangle

AdvancedTopic: Pattern Programs
Back

C++ Pascal's Triangle Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int rows;
    
    cout << "Enter number of rows: ";
    cin >> rows;
    
    for (int i = 0; i < rows; i++) {
        int num = 1;
        // Print spaces
        for (int j = 0; j < rows - i - 1; j++) {
            cout << " ";
        }
        // Print numbers
        for (int j = 0; j <= i; j++) {
            cout << num << " ";
            num = num * (i - j) / (j + 1);
        }
        cout << endl;
    }
    
    return 0;
}
Output
Enter number of rows: 5
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Understanding Pascal's Triangle

This program teaches you how to print Pascal's Triangle using nested loops in C++. Pascal's Triangle is a famous mathematical pattern where each number is the sum of the two numbers directly above it. It has many applications in mathematics, including binomial coefficients, probability, and combinatorics. This is an advanced pattern that combines mathematical formulas with nested loops.

---

1. What is Pascal's Triangle?

Pascal's Triangle looks like this (for 5 rows):

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

Key Properties:

Each row starts and ends with 1
Each number is the sum of the two numbers above it
The numbers are binomial coefficients
The triangle is symmetric

Example of the sum property:

Row 3: 1 2 1
The 2 in the middle = 1 + 1 (from row 2)
Row 4: 1 3 3 1
First 3 = 1 + 2 (from row 3)
Second 3 = 2 + 1 (from row 3)

---

2. Header File

#include <iostream>

Provides cout for output and cin for input.

---

3. Variable Declaration

int rows;

Stores the number of rows the user wants in Pascal's Triangle.

---

4. Taking Input

`cout << "Enter number of rows: ";`

cin >> rows;

Gets the number of rows from the user.

---

5. Understanding the Mathematical Formula

Each number in Pascal's Triangle can be calculated using the formula for binomial coefficients:

C(n, k) = n! / (k! * (n-k)!)

However, calculating factorials is inefficient. Instead, we use an iterative formula:

num = num * (i - j) / (j + 1)

Where:

i = row number (0-indexed)
j = position in row (0-indexed)
num = current number value

How it works:

Start with num = 1 for each row
For each position j in row i, calculate the next number using the formula
This efficiently generates each number without calculating factorials

---

6. Step-by-Step Breakdown

Let's trace through when rows = 5:

Row 0 (i = 0):

num = 1 (initialized)
Spaces: rows - i - 1 = 5 - 0 - 1 = 4 spaces
Print: 1
Output: 1 (4 spaces + 1)

Row 1 (i = 1):

num = 1 (reset for new row)
Spaces: 5 - 1 - 1 = 3 spaces
Position 0: Print num = 1
Position 1: num = num * (1 - 0) / (0 + 1) = 1 * 1 / 1 = 1
Print: 1 1
Output: 1 1 (3 spaces + 1 1)

Row 2 (i = 2):

num = 1 (reset)
Spaces: 5 - 2 - 1 = 2 spaces
Position 0: Print num = 1
Position 1: num = 1 * (2 - 0) / (0 + 1) = 1 * 2 / 1 = 2
Position 2: num = 2 * (2 - 1) / (1 + 1) = 2 * 1 / 2 = 1
Print: 1 2 1
Output: 1 2 1 (2 spaces + 1 2 1)

Row 3 (i = 3):

Similar process...
Output: 1 3 3 1

Row 4 (i = 4):

Similar process...
Output: 1 4 6 4 1

---

7. Code Explanation

for (int i = 0; i < rows; i++) {
    int num = 1;  // Start each row with 1
    for (int j = 0; j < rows - i - 1; j++) {

        cout << " ";
    }

    // Print numbers
    for (int j = 0; j <= i; j++) {

        cout << num << " ";
        num = num * (i - j) / (j + 1);  // Calculate next number
    }

    cout << endl;
}
    // Print spaces

Outer Loop (`i`)

:

Controls the row number (0 to rows-1)
Note: Uses 0-indexing (starts at 0)

Variable `num`

:

Initialized to 1 at the start of each row
This is the first number in each row (always 1)

First Inner Loop

(Spaces):

Condition: j < rows - i - 1
Prints spaces to center the triangle
Spaces decrease as we go down rows

Second Inner Loop

(Numbers):

Condition: j <= i
Prints i + 1 numbers in row i
For each position:
1.Print current num
2.Calculate next num using the formula

Formula: `num = num * (i - j) / (j + 1)`

:

This efficiently calculates the next binomial coefficient
No need for factorial calculations
Works because of the mathematical relationship between consecutive binomial coefficients

---

8. Why This Formula Works

The formula num = num * (i - j) / (j + 1) is derived from the relationship:

C(i, j+1) = C(i, j) * (i - j) / (j + 1)

This means:

If we know C(i, j), we can calculate C(i, j+1) using multiplication and division
Much faster than calculating factorials
Numerically stable for reasonable values

---

9. Visual Representation

For `rows = 5`:

Row 0: [4 spaces] [1]                    →     1
Row 1: [3 spaces] [1, 1]                 →    1 1
Row 2: [2 spaces] [1, 2, 1]              →   1 2 1
Row 3: [1 space]  [1, 3, 3, 1]          →  1 3 3 1
Row 4: [0 spaces] [1, 4, 6, 4, 1]        → 1 4 6 4 1

Sum Property Visualization:

     1
    1 1
   1 2 1    ← 2 = 1 + 1
  1 3 3 1   ← 3 = 1 + 2, 3 = 2 + 1
 1 4 6 4 1  ← 4 = 1 + 3, 6 = 3 + 3, 4 = 3 + 1

---

10. Key Concepts Demonstrated

1.

Mathematical Formulas in Code

: Implementing mathematical relationships directly in programming logic.

2.

Efficient Algorithms

: Using iterative formulas instead of calculating factorials (much faster).

3.

0-Indexing

: Understanding when and why to use 0-based indexing in loops.

4.

State Management

: Maintaining state (num) across iterations within a loop.

5.

Centered Patterns

: Combining spacing with number printing for visual appeal.

---

11. Applications of Pascal's Triangle

Pascal's Triangle has many real-world applications:

1.

Binomial Coefficients

: Used in expanding (a+b)^n

2.

Probability

: Calculating combinations in probability problems

3.

Combinatorics

: Finding number of ways to choose items

4.

Fibonacci Numbers

: Hidden patterns in Pascal's Triangle

5.

Sierpinski Triangle

: Fractal patterns emerge when coloring odd/even numbers

---

12. Common Mistakes

1.

Wrong initialization

: Not resetting num = 1 for each row

2.

Integer division

: The formula uses integer division, which works correctly for binomial coefficients

3.

Wrong loop bounds

: Using i <= rows instead of i < rows (0-indexing)

4.

Missing spaces

: Forgetting to print spaces before numbers

5.

Formula order

: Calculating num before printing (should print first, then calculate next)

---

13. Advanced Variations

Once you understand this, you can create:

-

Hollow Pascal's Triangle

: Only print 1s and edges

-

Colored Pascal's Triangle

: Color odd/even numbers differently

-

Pascal's Triangle with Modulo

: Show patterns with modulo arithmetic

-

3D Pascal's Triangle

: Extend to higher dimensions

---

Summary

The outer loop (i) controls the row number (0 to rows-1, 0-indexed).
Each row starts with num = 1.
The first inner loop prints spaces to center the triangle.
The second inner loop prints numbers:
Prints current num
Calculates next num using num = num * (i - j) / (j + 1)
After each row, endl moves to the next line.
This creates Pascal's Triangle where each number is the sum of the two numbers above it.

This program is essential for understanding mathematical programming, efficient algorithms, and how to implement mathematical formulas in code. It's a great example of combining mathematics with programming logic.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Pascal's Triangle

This C++ program is part of the "Pattern Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents