Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print Pascal's Triangle

C Code Example — Pattern Programs

ADVERTISEMENT

C Program to print Pascal's Triangle

Objective

Write a C program to print Pascal's Triangle using the factorial combination formula.

Algorithm / Approach

  1. Create a helper function fact(int a) that calculates the factorial of a number.
  2. Run an outer loop i from 0 to n.
  3. Print spaces to form the pyramid shape.
  4. Run an inner loop c from 0 to i.
  5. Calculate and print the binomial coefficient: fact(i) / (fact(c) * fact(i - c)).
  6. 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 i and column c is exactly iCc (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)
ADVERTISEMENT