A **C++ program** to generate a **Pascal’s triangle** which is as follows:

1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

<pre>#include<iostream> using namespace std; int fact(int); main() { int rows,i,j,k; cout<<"Enter the numbe of rows you want in the triangle:"; cin>>rows; for(i=0;i<rows;i++) { //Moving each row by rows-i spaces to get a triangular shape for(k=0;k<(rows-i);k++) cout<<" "; //Loop for printing each row for(j=0;j<=i;j++) cout<<" "<<fact(i)/(fact(j)*fact(i-j)); //nCr=n!/(r!*(n-r)!) cout<<endl; } } int fact(int i) { int value=1; while(i!=0) { value=value*i; i--; } return value; }</pre>

## Download the program Pascals-Triangle

I needed it…!

Thanks

That’s really slow, though (exponential in the number of rows you want to output) since you have to keep computing factorials over and over again.

It’s *much* faster to use the fact that each element is the sum of the two above it. This means you need to always store the last row you’ve computed, but that’s not a big deal if you are willing to spend O(n) space.

Hello Tom,

Thanks for ur comment, i will post the optimized code very soon.

guys.., how could you display this program like this:

*

*

* *

* *

* * *

* *

* *

*

*

given any value for the row..,

the same consept as above but displayed sideways.., tnx..,

#include

#include

void main()

{

clrscr();

int a[10][11];

int i,j;

for(i=0;i<=9;i++)

{

for(j=0;j<=10;j++)

a[i][j]=0;

}

a[0][1]=1;

for(i=1;i<=9;i++)

{

for(j=1;j<=10;j++)

{

a[i][j]=a[i-1][j-1]+a[i-1][j];

}

}

for(i=0;i=i-5;j–)

cout<<" ";

for(j=1;j<=10;j++)

{

if(a[i][j]!=0)

cout<<" "<<a[i][j];

}

cout<<"\n";

}

}

guys..wat abt dis program..

1

1 2

1 2 3

1 2 3 4