Program to Print Pascal Triangle

Beginner

Introduction

In this lab, we will learn how to write a C++ program to print Pascal Triangle. Pascal's triangle is a triangular array of binomial coefficients. It is named after the French mathematician Blaise Pascal, although other mathematicians studied it centuries before him in India, Persia (Iran), China, Germany, and Italy.

Create a new C++ file

Open the terminal to begin with the process of writing a C++ program to print Pascal's triangle.

Create a new C++ file named main.cpp in the ~/project directory using the following command:

touch ~/project/main.cpp

Write the program

Copy and paste the following code into the main.cpp file. This code allows you to print Pascal's triangle.

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
    int rows;
    cout << "Enter the number of rows to print Pascal's triangle: ";
    cin >> rows;
    cout << endl;

    for (int i = 0; i < rows; i++)
    {
        int number = 1;
        cout << setw(rows-i);

        for (int j = 0; j <= i; j++)
        {
            cout << number << " ";
            number = number * (i - j)/(j + 1);
        }
        cout << endl;
    }
    return 0;
}

Save and compile the program

Save the changes to the main.cpp file and compile it using the following command:

g++ main.cpp -o main

Run the program

Now, Run the C++ program using the following command:

./main

Summary

In this lab, we have written a C++ program to print Pascal's triangle. We hope that this lab will help you to understand the concept of Pascal's triangle and how to print it using C++ programming language.

Other Tutorials you may like