# C++ Program to Print Pascal’s Triangle

03/05/2024

Printing Pascal’s Triangle in C++ is a useful exercise to practice nested loops and understand combinatorial mathematics. Pascal’s Triangle is a triangular array where each entry is the sum of the two directly above it on the previous row. The outer edges of the triangle are populated with ones, and each number inside the triangle is the sum of the two numbers above it.

Here, we’ll write a C++ program that prompts the user to enter the number of rows they want in Pascal’s Triangle, and then outputs the triangle.

C++ Code:

#include <iostream>

using namespace std;

// Function to calculate factorial

int factorial(int n) {

int fact = 1;

for (int i = 1; i <= n; ++i) {

fact *= i;

}

return fact;

}

// Function to calculate binomial coefficient (n choose k)

int binomialCoefficient(int n, int k) {

return factorial(n) / (factorial(k) * factorial(n – k));

}

// Function to print Pascal’s Triangle

void printPascalsTriangle(int rows) {

for (int n = 0; n < rows; n++) {

for (int space = 1; space <= rows – n; space++) {

cout << ” “;

}

// Calculating and printing the values in each row

for (int k = 0; k <= n; k++) {

cout << binomialCoefficient(n, k) << ” “;

}

cout << endl;

}

}

int main() {

int rows;

// Asking the user for the number of rows

cout << “Enter the number of rows for Pascal’s Triangle: “;

cin >> rows;

// Printing Pascal’s Triangle

printPascalsTriangle(rows);

return 0;

}

Explanation:

1. Factorial Function:

This function computes the factorial of a given number, used in the calculation of the binomial coefficients.

1. Binomial Coefficient Function:

Computes the binomial coefficient using the factorial function. The binomial coefficient (𝑛𝑘)(kn​) is crucial for determining the values in Pascal’s Triangle.

1. Printing Pascal’s Triangle:

• Outer Loop: Iterates over each row of the triangle.
• First Inner Loop: Prints spaces to align the numbers properly, creating the triangular shape.
• Second Inner Loop: Computes and prints each number in the row using the binomial coefficient function.
2. Main Function:

Takes the number of rows from the user and calls the function to print Pascal’s Triangle.

Program Output:

If the user enters 5 for the number of rows, the output will be:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

This triangle visually represents the binomial coefficients, and the values correspond to combinations. Each number represents the number of ways to choose a subset of elements from a larger set where order does not matter. This program provides a foundational understanding of how loops and mathematical functions can be utilized to solve combinatorial problems in C++.