C++ Program to Print Pascal Triangle

This C++ Program which prints pascal’s triangle. The program takes number of rows as input and uses nested loops to print pascal’s triangle. The first inner loop creates the indentation space and the second inner loop computes the value of binomial coefficient, creates indentation space and prints the binomial coefficient for that particular column.

Here is source code of the C++ program which prints pascal’s triangle. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Print Pascal's Triangle
  3.  */
  4.  
  5. #include<iostream>
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     int rows;
  11.     cout << "Enter the number of rows : ";
  12.     cin >> rows;
  13.     cout << endl;
  14.  
  15.     for (int i = 0; i < rows; i++)
  16.     {
  17.         int val = 1;
  18.         for (int j = 1; j < (rows - i); j++)
  19.         {
  20.             cout << "   ";
  21.         }
  22.         for (int k = 0; k <= i; k++)
  23.         {
  24.             cout << "      " << val;
  25.             val = val * (i - k) / (k + 1);
  26.         }
  27.         cout << endl << endl;
  28.     }
  29.     cout << endl;
  30.     return 0;
  31. }

$ g++ main.cpp
$ ./a.out
Enter the number of rows : 5
 
                  1
 
               1      1
 
            1      2      1
 
         1      3      3      1
 
      1      4      6      4      1

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.