Pascal Triangle

Q. Write a C program to generate pascal triangle.
OR
Q. Write a C program to print following number triangle :




1






1
1




1
2
1


1
3
3
1
1
4
6
4
1


Ans.


How to build Pascal triangle:

To build the pascal triangle, start with "1" at the top, then continue placing numbers below it in a triangular pattern. Each number is build just sum of above two number, (except for the edge, which are all �1� and all numbers outside the Triangle are 0's). so

0 row = 1

1 row = adding the two numbers above them to the left and the right

         = (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



/*c program for making pascal triangle*/
#include<stdio.h>
#include<conio.h>
long calc( int );
int main()
{
 int i,j,row,pas;
 printf("Enter no. of rows in pascal triangle : ");
 scanf("%d", &row);
 for(i=0; i<row; i++)
 {
   for(j=0; j<=(row-i-1); j++)
     printf(" ");
   for(j=0; j<=i; j++)
   {
     pas=calc(i)/(calc(j)*calc(i-j));
     printf("%ld ",pas); //take single space
   }
   printf("\n");
 }
 getch();
 return 0;
}

long calc( int num)
{
 int x;
 long res=1;
 for(x=1; x<=num; x++)
   res=res*x;
 return (res);
}

Output:-
Output of pascal triangle C program
Figure: Screen shot for pascal triangle C program

Comments