Open In App

Pascal Triangle Program in C

Last Updated : 15 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Pascal’s Triangle is a triangular array of numbers where each number is the sum of the two numbers directly above it. The triangle starts with 1 at the top, and each subsequent row contains the coefficients of binomial expansions. In this article, we will learn how to print Pascal's Triangle in C.

pascal-300x241

Pascal’s Triangle is a triangular array of binomial coefficients in which the nth row contains binomial coefficients nC0nC1nC2, ……. 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:

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:

Screenshot-2024-12-03-171150

Let's take a look at the code implementation:

C
#include <stdio.h>
int main() {
  
    int n = 5; 

    // Outer loop to print each row
    for (int i = 0; i < n; i++) {
        
        // Print leading spaces for alignment
        for (int j = 0; j < n - i - 1; j++)
            printf(" ");

        // Print values in row
        int val = 1;
        for (int k = 0; k <= i; k++) {
            printf("%d ", val);
          
            // Calculate the next value in the row
            val = val * (i - k) / (k + 1);  
        }
        printf("\n");
    }

    return 0;
}

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

Explanation: In this method, the outer loop iterates through each row of Pascal's Triangle, and the inner loop calculates and prints each value in the row. The first and last values in each row are hardcoded as 1. For the intermediate values, the formula value = value * (i - j) / (j + 1) is used to compute the binomial coefficients based on Pascal's Triangle’s recursive property. Spaces are printed before the numbers to align the triangle properly.


Next Article

Similar Reads