Pascal Triangle Program in C with explanation

pascal triangle pattern program in c

In this tutorial we are going to learn writing program in C to print pascal triangle.

But before directly moving on writing program first lets know

What is Pascal Triangle?

Pascal Triangle starts with row n = 0 where there is only one entry 1.

And it grows row-wise toward the right by adding the previous and next item of the previous row.

For example:

  • The initial number in the first row is 1 (the sum of 0 and 1),
  • In second row, addition of 0+1 = 1 and 1+0 = 1. So 1    1 in second row.
  • When we move on 3rd row then 0+1 = 1, 1+1=2 and 1+0 = 1. So elements of triangle in 3rd row is 1   2    1.

Following this approach pascal triangle grows.

C Program to print Pascal’s Triangle

#include<stdio.h>
#include<conio.h>
void main() {
    int n, temp=1,i,j,k;
    printf("Enter number of rows: ");
    scanf("%d", &n);
    for (i=0; i<n; i++) {
        for (k=1; k <= n-i; k++)
            printf(" ");
        for (j=0; j<=i; j++) {
            if (j==0 || i==0)
                temp = 1;
            else
                temp=temp*(i-j+1)/j;
            printf("%2d", temp);
        }
        printf("\n");
    }
    getch();
}

Output

Enter number of rows: 5
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

Leave a Comment