Print Pascal’s triangle of Nth row in C++
In this tutorial, we will learn how to print Pascal’s triangle in C++ with an algorithm.
Pascal’s triangle is a 2-D array (2-D triangular array) of binomial coefficients. It starts from 1 at the top, then each number placed below in the triangular pattern is the sum of the above two numbers.
Algorithm: Pascal’s triangle
- declares an initialize a variable ‘n’ for the number of rows.
- start an outer loop for ‘i’ to ‘n’.
- make an inner loop for ‘j’ to “n-1″, print a single space (” “) and close the loop.
- make another inner loop for ‘j’ to ‘i’
- print nCr or C(n, r) for each ‘i’ and ‘j’ and close the loop. (means iCj or C(i, j))
- change the line after each second inner loop (for every ‘i’ after the inner loop)
C++ program to print Pascal’s triangle
#include<iostream>
using namespace std;
int factorial(int);
int nCr(int, int);
int main(){
int n, i, j;
cout<<"Enter the number of rows: ";
cin>>n;
for(int i = 0;i < n; i++){
//first inner loop to print spaces
for(j = 0; j <= n-i; j++)
cout<<" ";
//second inner loop to print combination for each i and j
for(j = 0; j <= i; j++)
cout<<nCr(i, j)<<" ";
cout<<endl;
}
return 0;
}
//to find combination or nCr
int nCr( int n, int r){
return (factorial(n) / (factorial(n - r) * factorial(r)));
}
//to find factorial
int factorial(int n){
int fact = 1;
for(int i = 1; i <= n; i++)
fact *= i;
return fact;
}Output:
Enter the number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1Time complexity: O(n^2)
you may also read:
Leave a Reply