DEV Community

Cover image for C++ Program to Print a Pascal Triangle
Labby for LabEx

Posted on • Originally published at labex.io

C++ Program to Print a Pascal Triangle

Introduction

In this lab, we will learn how to program in C++ to print a Pascal triangle. A Pascal's triangle is a triangular array of binomial coefficients. The triangle can be formed by using the coefficients as the entries. Pascal's triangle can be used to calculate combinations and calculate binomial expansion. In this lab, we will learn how to create a C++ program that can be used to print the Pascal triangle.

Create a new C++ file

First, we need to create a new C++ file, which can be done by running the following command in the terminal:

touch ~/project/main.cpp
Enter fullscreen mode Exit fullscreen mode

Add code to the newly created file

Next, we need to add the following code to the newly created file:

#include <iostream>
using namespace std;

int main()
{
    int rows, coef = 1;

    cout << "Enter number of rows: ";
    cin >> rows;

    for(int i = 0; i < rows; i++)
    {
        // Print spaces
        for(int space = 1; space <= rows-i; space++)
            cout <<"  ";

        // Calculate coefficients
        for(int j = 0; j <= i; j++)
        {
            if (j == 0 || i == 0)
                coef = 1;
            else
                coef = coef*(i-j+1)/j;

            // Print coefficients
            cout << coef << "   ";
        }
        // Move to next line
        cout << endl;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Compile and run the program

We can compile and run the program using the following command:

g++ ~/project/main.cpp -o ~/project/main && ~/project/main
Enter fullscreen mode Exit fullscreen mode

Summary

You have just learned how to create a C++ program that can print Pascal's triangle. A Pascal's triangle is a useful way to display binomial coefficients. It can also be used to calculate combinations and binomial expansion. To create the program, we used for loop, if else statement, variables, cout object, and cin object. By following the steps outlined in this tutorial, you can now create your own C++ program that can print Pascal's triangle.


Want to learn more?

Join our Discord or tweet us @WeAreLabEx ! 😄

Top comments (0)