A C++ program to generate a Pascal’s triangle

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

Subscribe / Share

Article by Satish Gandham

Authors bio is coming up shortly. Satish Gandham tagged this post with: , Read 10 articles by Satish Gandham
7 Comments Post a Comment
  1. HacK_MiNDeD says:

    I needed it…!
    Thanks

  2. Tom says:

    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.

  3. Satish Gandham says:

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

  4. dayle says:

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

    *
    *
    * *
    * *
    * * *
    * *
    * *
    *
    *

    given any value for the row..,

  5. dayle says:

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

  6. sanket says:

    #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";
    }
    }

  7. raks says:

    guys..wat abt dis program..
    1
    1 2
    1 2 3
    1 2 3 4

Leave a Reply




Tip

When downloading untested code, make sure you have antivirus software installed.