Pascal's Triangle |
#include<iostream>
using namespace std; unsigned int factorial(unsigned int const num){ if( num <=1 ) return 1; else return num*factorial(num-1); } int main( void ){ int row = 0; cout<<"Enter the number of rows: "; cin>>row; //Method 1 for(unsigned int n=0;n<row;++n){ //spacing before row depends on how many rows there are //row-i = number of space needed before row starts for(unsigned int j=1;j<(row-n);++j){ cout<<" "; } unsigned int n_factorial = factorial(n); //printing the binomial coefficient using combination formula //Number of binomial coefficient on each line // is equivalent to the current row number (i.e., the counter i) //n choose k or nCk = n!/(k!(n-k)!) for(unsigned int k=0;k<=n;++k){ cout<<" "<<n_factorial/(factorial(n-k)*factorial(k)); } cout<<endl<<endl; } //Method 2 for(unsigned int n=0;n<row;++n){ for(unsigned int j=1;j<(row-n);++j){ cout<<" "; } unsigned int coeff = 1; for(unsigned int k=0;k<=n;++k){ cout<<" "<<coeff; coeff = coeff*(n-k)/(k+1); } cout<<endl<<endl; } return 0; }
Output:
Enter number of rows: 5 Method 1: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Method 2: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Comments
Post a Comment