HomeC ProgrammingC Program to Print Pascal Triangle

C Program to Print Pascal Triangle

This C program prints Pascal’s triangle based on the number of rows entered by the user. Pascal’s triangle is a triangular array of numbers where each number is the sum of the two numbers directly above it.

Problem statement

Write a C program to print Pascal’s triangle based on the number of rows entered by the user.

C Program to Print Pascal Triangle

#include <stdio.h>

long binomialCoeff(int n, int k) {
    if (k == 0 || k == n)
        return 1;
    return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);
}

void printPascalTriangle(int n) {
    for (int line = 0; line < n; line++) {
        for (int i = 0; i <= line; i++)
            printf("%ld ", binomialCoeff(line, i));
        printf("\n");
    }
}

int main() {
    int rows;

    printf("Pascal's Triangle\n");

    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    printf("Pascal's Triangle with %d rows:\n", rows);
    printPascalTriangle(rows);

    return 0;
}

How it works?

  1. The program uses the binomialCoeff function to calculate the value of each element in Pascal’s triangle. The binomialCoeff function is a recursive function that calculates the binomial coefficient using the formula C(n, k) = C(n-1, k-1) + C(n-1, k).
  2. The printPascalTriangle function iterates through each line of the triangle and calls the binomialCoeff function to calculate the value of each element in the line.
  3. The main function prompts the user to enter the number of rows they want in Pascal’s triangle.
  4. The printPascalTriangle function is called with the user’s input as the argument, and it prints the Pascal’s triangle.

Input/Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...