C Program to print Pascal's Triangle
Objective
Write a C program to print Pascal's Triangle using the factorial combination formula.
Algorithm / Approach
- Create a helper function
fact(int a)that calculates the factorial of a number. - Run an outer loop
ifrom 0 ton. - Print spaces to form the pyramid shape.
- Run an inner loop
cfrom 0 toi. - Calculate and print the binomial coefficient:
fact(i) / (fact(c) * fact(i - c)). - Print a newline.
main.c
#include<stdio.h>
int fact(int a);
int main( ) {
int i, j,n, c;
printf("Enter the value for 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("%d",fact(i)/(fact(c)*fact(i-c)));
}
printf("\n");
}
return 0;
}
int fact(int a)
{
int i,result =1;
for(i=1; i <= a; i++) {
result = result*i;
}
return result;
}
Expected Output
1 1 1 1 2 1 1 3 3 1
Explanation of the Program
- Pascal's Triangle is a famous mathematical pattern where each number is the sum of the two numbers directly above it.
- Instead of using complex 2D arrays to add the numbers, a more elegant mathematical approach is to use the combinations formula (nCr). The value at row
iand columncis exactlyiCc(i factorial divided by (c factorial * (i-c) factorial)).
Complexity
Time Complexity
O(n^3) - Because factorial is calculated repeatedly inside nested loops.
Space Complexity
O(1)