Home »
C++ programs »
C++ Most popular & searched programs
C++ Program to print a Pascal Triangle upto N depth
This C++ program will read the depth and print the Pascal Trainable up to input depth.
Submitted by Abhishek Pathak, on April 04, 2017 [Last updated : February 27, 2023]
Printing a Pascal Triangle upto N depth
Pascal Triangle is a triangular array of binomial coefficients, named after Blaise Pascal. In this triangle, the subsequent rows are relative to the numbers in the previous row. The triangle is constructed in following manner, at the top most row, there is only a single element, usually 1. The next row is written in such a way that the element represent the sum of the top left and top right element, therefore leaving the space blank directly under the top element. Here’s a picture that explains it better. [Read more: Pascal's triangle]
In this program, we will print a pascal triangle up to n depth or n rows. Here the number of rows (n) will be entered by users and then a pascal triangle will be generated in a 2D manner.
The leftmost and the rightmost numbers in the row are represented by 1. Since the top left of each row is taken as 0, so 0+1 gives 1. Here, as you can see, 2 is represented by addition of top-left 1 and top-right 1. Similarly, 3 in the next row is the result of addition of top-left 1 and top-right 2. This continues upto n number of rows.
C++ code to print a Pascal Triangle upto N depth
#include <iostream>
using namespace std;
int main()
{
int h, digit;
cout << "Enter Height: ";
cin >> h;
cout << endl;
if (h < 1) {
cout << "Pascal Triangle is not possible!";
}
else {
for (int i = 0; i < h; i++) {
for (int j = 0; j <= i; j++) {
if (i == 0 || j == 0)
digit = 1;
else
digit = digit * (i - j + 1) / j;
cout << digit << " ";
}
cout << "\n";
}
}
return 0;
}
Output
Enter Height: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Solution Explanation
In this program, first of all we are checking if user enters a valid height. If h is less than 1, that means either 0 or negative, we can’t form the pascal triangle.
Then, we are taking two loops, one to control rows (outer loop or the i loop) and other to control columns (the j loop). The digit variable will hold the value to be printed. In the first if statement, we are placing 1 at the first column of every row.
In the else part, we are simply multiplying the digit variable with a small math logic. The (i-j+1)/j calculates the relative position.