Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

Program for Pascal Triangle in C and C++

$
0
0

Here I have shared simple program for pascal triangle in C and C++.

Basically Pascal’s triangle is a triangular array of binomial coefficients. An example for how pascal triangle is generated is illustrated in below image. If you have any doubts then you can ask it in comment section.

Each number is the sum of the two directly above it.

Pascal Triangle Animated

 

Program for Pascal Triangle in C

#include<stdio.h>

//function to calculate factorial
long fact(int x)
{
	int i;
	long f=1;
	
	for(i=1;i<=x;++i)
	{
		f=f*i;
	}	
	
	return f;
}

int main()
{
	int i,j,k,n;
	printf("How many lines? ");
	scanf("%d",&n);
	
	for(i=0;i<n;++i)
	{
		//loop to print spaces at starting of each row
		for(j=1;j<=(n-i-1);++j)
		{
			printf(" ");
		}
		
		//loop to calculate each value in a row and print it
		for(k=0;k<=i;++k)
		{
			printf("%ld ",fact(i)/(fact(i-k)*fact(k)));
		}
		
		printf("\n");	//print new line after each row
	}
	
	return 0;
}

 

Program for Pascal Triangle in C++

#include<iostream>

using namespace std;

//function to calculate factorial
long fact(int x)
{
	int i;
	long f=1;
	
	for(i=1;i<=x;++i)
	{
		f=f*i;
	}	
	
	return f;
}

int main()
{
	int i,j,k,n;
	cout<<"How many lines? ";
	cin>>n;
	
	for(i=0;i<n;++i)
	{
		//loop to print spaces at starting of each row
		for(j=1;j<=(n-i-1);++j)
		{
			cout<<" ";
		}
		
		//loop to calculate each value in a row and print it
		for(k=0;k<=i;++k)
		{
			 cout<<fact(i)/(fact(i-k)*fact(k))<<" ";
		}
		
		cout<<"\n";	//print new line after each row
	}
	
	return 0;
}

 

Output

Program for Pascal Triangle in C and C++

The post Program for Pascal Triangle in C and C++ appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles