Open In App

Pascal Triangle Program in C

Improve
Improve
Like Article
Like
Save
Share
Report

Pascal’s Triangle is a pattern in which the first row consists of a single number 1, and each row begins and ends with the number 1. The numbers in between are obtained by adding the two numbers directly above them in the previous row.

In this article, we will see how to print Pascal’s triangle in C programming language.

c pascal triangle

Pascal’s Triangle is a triangular array of binomial coefficients in which the nth row contains binomial coefficients nC0, nC1, nC2, ……. nCn.

nCr can be represented as C(n,r) and this represents the nth row’s rth element in Pascal’s pyramid. The idea is to calculate C(n, r) using C(n, r-1). It can be calculated in O(1) time using the following formula:

C(n, r) = \frac{C(n, r-1) * (n - r + 1)}{r}

This is an efficient way to calculate the binomial coefficients using the values from the previous row.

C program to Print Pascal’s Triangle

C

// C program to print Pascal’s Triangle
// using combinations in O(n^2) time
// and O(1) extra space function
#include <stdio.h>
void printPascal(int n)
{
    for (int line = 1; line <= n; line++) {
        for (int space = 1; space <= n - line; space++)
            printf("  ");
        // used to represent C(line, i)
        int coef = 1;
        for (int i = 1; i <= line; i++) {
            // The first value in a line
            // is always 1
            printf("%4d", coef);
            coef = coef * (line - i) / i;
        }
        printf("\n");
    }
}
  
// Driver code
int main()
{
    int n = 5;
    printPascal(n);
    return 0;
}

                    

Output
           1
         1   1
       1   2   1
     1   3   3   1
   1   4   6   4   1

Complexity Analysis

Time Complexity: O(n2)
Auxiliary Space: O(1)



Last Updated : 18 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads