C++ Program to display Pascal Triangle

In this tutorial, we will write a C++ program to display pascal’s triangle. Before that, you may go through the following topic in C++.


C++ Program to display Pascal Triangle

C++ program to print pascal’s triangle: The program takes the user input for the number of rows the user wants in a pascal triangle and by nesting the for loop, the program displays the triangle.

#include <iostream>
using namespace std;

int main()
{
  int rows, i, j, k;
  cout << "Enter the number of rows: ";
  cin >> rows;

  for (i = 0; i < rows; i++)
  {
    int val = 1;
    for (j = 1; j < (rows - i); j++)
      cout << "   ";

    for (k = 0; k <= i; k++)
    {
      cout << "      " << val;
      val = val *(i - k) / (k + 1);
    }

    cout << endl << endl;
  }

  return 0;
}

Output:

Enter the number of rows: 6
                     1

                  1      1

               1      2      1

            1      3      3      1

         1      4      6      4      1

      1      5      10      10      5      1