How to print pascal’s triangle in C++
In this tutorial, we will learn how to print pascal’s triangle in c++. A Pascal’s triangle is a simply triangular array of binomial coefficients. Each number can be represented as the sum of the two numbers directly above it. For example-
Print pascal’s triangle in C++
There are various methods to print a pascal’s triangle. Below is an interesting solution.
If we look closely at the Pascal triangle and represent it in a combination of numbers, it will look like this.
Look at the 4th line. It follows a pattern. The numbers range from the combination(4,0)[n=4 and r=0] to combination(4,4). This pattern follows for the whole triangle and we will use this logic in our code.
The Formula for combination is simple(shown in image):
First, we will calculate the numerator separately and then the denominator.
Note: The first line always prints 1.(So we print it in the main function only)
C++ Code
Here, is the final code implementation:
#include<iostream> using namespace std; int res=1; int fact(int n) { if(n==1||n==0) { return 1; } else { res=n*fact(n-1); return res; } } int combination(int n,int r) { //int num=0,den=0; int num=fact(n); int den=fact(n-r)*fact(r); int result=num/den; return result; } void pascal(int curline,int nlines) { if(curline==nlines) return; int k=curline+1; for(int j=1;j<=k;j++) { int dig=combination(curline,j-1); cout<<dig<<'\t'; } cout<<endl; pascal(curline+1,nlines); } int main() { int nlines; cin>>nlines; cout<<"1"<<endl;//The first line always contains 1 pascal(1,nlines); }
Input:
6
Output:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
Another code to do the same
Pascal’s triangle:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1
Building Pascal’s triangle:
- On the first top row, we will write the number “1.”
- In the next row, we will write two 1’s, forming a triangle.
- Then see the code
1 1 1 \ / 1 2 1 \/ \/ 1 3 3 1
Let us try to implement our above idea in our code and try to print the required output. These types of problems are basically asked in company exams like TCS which just test your basic coding skills.
Program to print Pascal’s triangle
C++ source code:
// Program to Print pascal’s triangle #include<bits/stdc++.h> using namespace std; int main() { int rows, first=1, space, i, j; cout<<"\nEnter the number of rows you want to be in Pascal's triangle: "; cin>>rows; cout<<"\n"; for(i=0; i<rows; i++) { for(space=1;space<=rows-i;space++) { cout<<" "; } for(j=0;j<=i;j++) { if(j==0 || i==0) first= 1; else first=first*(i-j+1)/j; cout <<first<<" "; } cout<<"\n"; cout<<"\n"; } return 0; }
Input/Output:
Enter the number of rows you want to be in Pascal's triangle: 7 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1
Also, refer to these similar posts:
Count the number of occurrences of an element in a linked list in c++
Create all possible strings from a given set of characters in c++
Thank you! Please comment for suggestions
Leave a Reply