Pascal Triangle C Program - C program to print Pascal triangle using for loop
Learn C - C tutorial - c program of print pascal triangle using for loop - C examples - C programs
C program to print Pascal triangle using for loop
- Pascal’s triangle is that all the numbers outside the triangle are “0”s.
- To build the triangle, start with a “1” at the top, the continue putting numbers below in a triangular pattern so as to form a triangular array.
- So, each new number added below the top “1” is just the sum of the two numbers above, except for the edge which are all “1”s.
- This can be summarized as:
0 row =1
1 row = (0+1), (1+0) = 1, 1
2 row = (0+1), (1+1), (1+0) = 1, 2, 1
3 row = (0+1), (1+2), (2+1), (1+0) = 1, 3, 3, 1
4 row = (0+1), (1+3), (3+3), (3+1), (1+0) = 1, 4, 6, 4, 1
5 row = (0+1), (1+4), (4+6), (6+4), (4+1), (1,0) = 1, 5, 10, 10, 5,1
Sample Code
#include <stdio.h>
long fact(int num)
{
long f=1;
int i=1;
while(i<=num)
{
f=f*i;
i++;
}
return f;
}
int main()
{
int l=6,i,j;
printf("no. of lines: 6\n");
for(i=0; i<l; i++)
{
for(j=0; j<l-i-1; j++)
printf(" ");
for(j=0; j<=i; j++)
printf("%d ",fact(i)/(fact(j)*fact(i-j)));
printf("\n");
}
return 0;
}
Output
no. of lines: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1