C Program to Print Pascal's Triangle

Write a C Program to Print Pascal's Triangle



What is Pascal's Triangle ?

Pascal's Triangle is a triangular array of binomial co-efficient. It is constructed by summing adjacent elements in preceding rows.
Pascal’s triangle can be used as an instance of binomial coefficient and binomial theorem.


Problem Definition

We have to write a C program that will print pascal's triangle.


Solution/Source Code

Here is the Source C code to print Pascal's Triangle. Output results are also shown below.



  
    #include <stdio.h>
    int main() {
       int rows, co = 1, space, i, j;
       printf("Enter the number of rows: ");    // total numbers of rows in pascal's triangle
       scanf("%d", &rows);
       for (i = 0; i < rows; i++) {      // outer loop iteration for diaplying rows
          for (space = 1; space <= rows - i; space++)
             printf("  ");          // space for every rows starting
          for (j = 0; j <= i; j++) {       // inner loop to display pascal triangle values
             if (j == 0 || i == 0)
                co = 1;
             else
                co = co * (i - j + 1) / j;      // calculate the coefficients
             printf("%4d", co);
          }
          printf("\n");
       }
       return 0;
    }
    

Output Test case 1:

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

--------------------------------
    

Comments

Also Check Out

Write a C program to convert Infix to Postfix Expression

C Program to search element from a sorted array using Binary Search