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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #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:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |