2.DS -Lab -C Program to display Pascal Triangle using the binomial function(Part A)

C Program to display Pascal Triangle using the binomial function

Theory : The Pascal triangle is among the most well-known pattern puzzles. It organizes the figures in a triangle-shaped pattern. In other terms, it is an array of binomial coefficients in the form of a triangle. There are several approaches to implement the Pascal Triangle program in C, including a brute force approach and code optimization to lessen time and space complexity.

    What is a Pascal Triangle? 
    Pascal Triangle is a triangular arrangement (array) of numbers that shows the coefficients if a binomial expression is expanded. The numbers inside Pascal's triangle pattern are designed in such a way that each number will be the sum of the nearest two numbers in the above row of the triangle and the numbers at the extremes of each row of the triangle will be 1. It is a triangular array of binomial coefficients which are widely used in the problems of algebra, probability theory, and Combinatorics. The Pascal triangle is a special triangle named after the french mathematician Blaise Pascal. Generally, the Pascal triangle is used to find the outcome of a coin, coefficients of binomial expansion in probability, etc.


ALGORITHM : 
Step 1: Start
Step 2: Declare a recursive function binomial_coefficient(n, k).
Step 3: If k is equal to 0 or k is equal to n, return 1.
Step 4: Otherwise, return binomial_coefficient(n - 1, k - 1) + binomial_coefficient(n - 1, k).
Step 5: Input the number of rows (num_rows) for Pascal's Triangle.
Step 6: Iterate through each row (i) from 0 to num_rows-1.
Step 7: Print spaces for (num_rows - i - 1) times.
Step 8: Iterate through each element (j) in row i from 0 to i.
Step 9: Print the result of binomial_coefficient(i, j) followed by a space.
Step 10: Move to the next line after each row.
Step 11: End

Source Code :

#include <stdio.h> 
int main() {
int rows, coef = 1, space, i, j; //Enter the number of rows
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) //Inner Loop 1 to give space
{
for (space = 1; space <= rows - i; space++)
printf("  ");
for (j = 0; j <= i; j++) //Inner Loop 2 to calculate coef
{
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}


OUTPUT : 
Enter the number of rows for Pascal Triangle: 5
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 







No comments:

Post a Comment