Pascal Triangle Program in C
Last Updated :
18 Jul, 2023
Pascal’s Triangle is a pattern in which the first row consists of a single number 1, and each row begins and ends with the number 1. The numbers in between are obtained by adding the two numbers directly above them in the previous row.
In this article, we will see how to print Pascal’s triangle in C programming language.
Pascal’s Triangle is a triangular array of binomial coefficients in which the nth row contains binomial coefficients nC0, nC1, nC2, ……. 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:
This is an efficient way to calculate the binomial coefficients using the values from the previous row.
C program to Print Pascal’s Triangle
C
#include <stdio.h>
void printPascal( int n)
{
for ( int line = 1; line <= n; line++) {
for ( int space = 1; space <= n - line; space++)
printf ( " " );
int coef = 1;
for ( int i = 1; i <= line; i++) {
printf ( "%4d" , coef);
coef = coef * (line - i) / i;
}
printf ( "\n" );
}
}
int main()
{
int n = 5;
printPascal(n);
return 0;
}
|
Output 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Complexity Analysis
Time Complexity: O(n2)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...