C++ program to print Pascal’s and Floyd’s triangle


In this example, you are going to learn about an easy C++ program to print Pascal’s and Floyd’s triangle.
C++ program to print Pascal's and Floyd's triangle

Pascal’s Triangle

It is a triangular array of the binomial coefficients which is named after French mathematician Blaise Pascal.

Floyd’s Triangle

It is a right-angled triangular array of natural numbers which is named after Robert Floyd.

There are many ways to print Pascal triangle in C++ as well as Floyd triangle in C++.

Example: C++ program to print Pascal’s triangle

//Pascal triangle in C++
#include <iostream>
using namespace std;

int main()
{
   int n, i, j, c = 1, s;

   cout << "Enter number of rows to print in Pascal triangle: ";
   cin >> n;

   //for loop continues till the number of rows entered by the user
   for(i = 0; i < n; i++)
   {
      //for loop to print required number of space
      for(s = 1; s <= n - i; s++)
         cout << " ";

      //for loop to print number in triangle
      for(j = 0; j <= i; j++)
      {
         //first and last value of every row is 1
         if (j==0 || i==0)
            c = 1;
         else
            c = c *( i - j + 1) / j;

         cout << c << " ";
      }
      cout << endl;
   }

   return 0;
}

Output

pascal triangle in c++

Example: C++ program to print Floyd’s triangle

//Floyd's triangle in C++
#include <iostream>
using namespace std;

int main()
{
   int r, i, j, num = 1;

   //number of rows to print
   cout << "Enter number of rows for Floyd's triangle: ";
   cin >> r;

   //for loop responsible for number of rows
   for(i = 1; i <= r; i++)
   {
      //for loop responsible for number of columns
      for(j=1; j <= i; ++j)
      {
         cout << num++ << " "; //print number starting from 1
      }
      //prints new number in next line
      cout << endl;
   }

   return 0;
}

Output

floyd's triangle in c++