Pascal's Triangle

Program to print Pascal's triangle

C++Advanced
C++
#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

Pascal's Triangle in C++

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.

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

Understanding the Mathematical Formula

Each number in Pascal's Triangle can be calculated using the formula for binomial coefficients. 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

Algorithm

  1. For each row i (0 to rows-1):
    • Initialize num = 1 (first number in each row)
    • Print spaces for centering
    • For each position j in row i:
      • Print current num
      • Calculate next num using the formula
    • Move to next line

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.