Archives for

C++

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

Page 2 of 2«12