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

Pascal's triangle has each number equal to the sum of the two numbers above it. We calculate each number using the formula: num = num * (i - j) / (j + 1). This generates binomial coefficients. The triangle starts with 1 at the top.

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.

Table of Contents