C Program to print Pascal Triangle
Last updated on September 24, 2020
What is Pascal Triangle? #
The Pascal triangle is a triangular array of binomial coefficients. It looks like this:
1 2 3 4 5 6 | row -> 0 1
row -> 1 1 1
row -> 2 1 2 1
row -> 3 1 3 3 1
row -> 4 1 4 6 4 1
row -> 5 1 5 10 10 5 1
|
The following is a formula to compute the value at any given place in the triangle:
\[
\begin{pmatrix}n\\k\end{pmatrix} = \frac{n!}{k!(n-k)!}
\]
where n
stands for the row number and k
stands for the column number. Note that the rows start from 0
and also the leftmost column is 0
. So, to find out the value at 4th row, 2nd col, we do this:
\[
\begin{pmatrix}4\\2\end{pmatrix} = \frac{4!}{2!(4-2)!} = \frac{4!}{2!2!} = \frac{4*3}{2*1} = 6
\]
The following is a C program which prints the pascal triangle based upon the number of rows entered by the user:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | /**************************************
* C Program to print Pascal Triangle
***************************************/
#include<stdio.h> // include stdio.h
unsigned long int factorial(unsigned long int);
int main()
{
int n;
printf("Enter number of rows: ");
scanf("%d", &n);
printf("\n");
// loop for number of rows
for(int i = 0; i <= n; i++)
{
// loop to print leading spaces at each line
for(int space = 0; space < n - i; space++)
{
printf(" ");
}
// loop to print numbers in each row
for(int j = 0; j <= i; j++)
{
printf("%-5d ", factorial(i) / (factorial(j) * factorial(i-j) ) );
}
// print newline character
printf("\n");
}
return 0;
}
unsigned long int factorial(unsigned long int n)
{
unsigned long int f = 1;
while(n > 0)
{
f = f * n;
n--;
}
return f;
}
|
Expected Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Enter number of rows: 10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
|
Recommended Reading:
- C Program to calculate the difference of two dates in years, months and days
- C Program to calculate the day of year from the date
- C Program to print the date in legal form
- C Program to print various triangular patterns
- C Program to print Floyd’s Triangle
Load Comments