C and C++ Program to Display Pascal's Triangle

This post gives C and C++ programs to display given number of rows of pascal's triangle. Thenuser can enter the number of rows of pascal triangle to be displayed.

C Program:

#include<stdio.h>

#include<conio.h>

long factorial(int);

main()

{

int i, n, c;

printf("Enter the number of rows you wish to see in pascal triangle\n");

scanf("%d", &n);

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

{

for (c = 0; c <= (n - i - 2); c++)

printf(" ");

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

printf("%ld ", factorial(i) / (factorial(c) * factorial(i - c)));

printf("\n");

}

getch();

}



long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result * c;
return (result);
}


C++ Program:
 
#include<iostream.h>
#include<conio.h>
long factorial(int);
void main()
{
int i,n,c;
cout<<"Enter the number of rows you wish to see in pascal's triangle";
cin>>n;
for(i=0;i<n;i++)
{
for(c=0;c<=(n-i-2);c++)
cout<<" ";
for(c=0;c<=i;c++)
cout<<(factorial(i)/(factorial(c)*factorial(i-c)))<<" ";
cout<<"\n";
}
getch();
}
long factorial(int n)
{int c;
long result=1;
for(c=1;c<=n;c++)
result=result*c;
return(result);
}

No comments :

Post a Comment