Program to create a 2-D matrix representing the Pascal’s triangle.

#include<iostream>
#include<iomanip> using namespace std; int main() { int n,i,j,k; cout<<"enter the row number upto pascals triangle has to print: "; cin>>n; k=n-2; int a[n][n]; cout<< setw(n)<<1<<"\n"<<setw(n-1)<< 1<<setw(3)<< 1<<"\n"; for(i=2;i<n;i++) { cout<<setw(k)<<1; // starting 1 in each row for(j=1;j<i;j++) { a[i-1][0]=a[i-1][i-1]=1; a[i][j]=a[i-1][j-1] + a[i-1][j]; // pascals traingle using 2d array cout<<setw(3)<<a[i][j]<< setw(3); // the middle values are printed } cout<< 1 <<"\n"; // ending 1 in each row k--; } return 0; }



Here u can see, first the no of rows have to be given as input.That much size of the array is created at the initialization time.It can be created as dynamically also. The first 2 rows are printed manually. For the 3rd row it is through the loop. setw function will take care of space between the numbers as for our required space.