C Program to Print Pascal's Triangle

1. Introduction

Pascal's Triangle is a triangular array of the binomial coefficients that has applications in mathematics, computer science, and engineering. Each number is the sum of the two numbers directly above it. This blog post will guide you through writing a C program to print Pascal's Triangle, demonstrating the use of loops and conditional statements in creating complex patterns.

2. Program Steps

1. Prompt the user to enter the number of rows for Pascal's Triangle.

2. Implement a loop to handle the printing of each row.

3. Use nested loops within the main loop to calculate and print the values in each row, based on the binomial coefficient.

3. Code Program

#include <stdio.h>

long factorial(int n) {
    long f = 1;
    for(int i = 2; i <= n; i++)
        f *= i;
    return f;
}

long comb(int n, int r) {
    return factorial(n) / (factorial(r) * factorial(n - r));
}

int main() {
    int rows, i, j;

    // Asking for user input
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    for(i = 0; i < rows; i++) {
        // Printing leading spaces
        for(j = 0; j < rows - i - 1; j++) {
            printf(" ");
        }
        // Printing numbers
        for(j = 0; j <= i; j++) {
            printf("%ld ", comb(i, j));
        }
        printf("\n");
    }

    return 0;
}

Output:

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

Explanation:

1. The program includes the stdio.h library to enable input and output operations.

2. Two functions, factorial and comb, are defined to calculate the factorial of a number and the binomial coefficient, respectively.

3. The main function starts by declaring integer variables rows, i, and j for storing the number of rows and controlling loops.

4. The user is prompted to enter the number of rows for Pascal's Triangle.

5. A loop iterates through each row, with a nested loop to print the correct number of leading spaces for alignment.

6. Another nested loop calculates and prints the binomial coefficients for each position in the row using the comb function, which utilizes the factorial function to calculate combinations.

7. After printing all numbers in a row, a newline character is printed to move to the start of the next line.

8. The program ends with return 0;, indicating successful execution.


Comments