Pascal's Triangle in the C programming language:
#include <stdio.h>
#define X 15
int main(){
int tri[X][X];
for (int i=0;i<X;i ) {
tri[i][0]=1;
for(int k=X-1;k>i;k--) {
tri[i][k]=0;
}
for(int j=1;j<i 1;j ) {
tri[i][j]=tri[i-1][j-1] tri[i-1][j];
}
}
//To give the correct values to all number set elements
for (int m=0;m<X;m ) {
printf("%d\t",tri[m][0]);
for (int n=1;n<m 1;n ) {
printf("%d\t",tri[m][n]);
}
printf("\n");
}
//to print them
return 0;
}
I suspect there's a better way to solve this program which uses less memory storage, and I'd like to find a better solution to this C program.
What is the most optimized way to output Pascal's Triangle in C?
CodePudding user response:
Numbers in rows of Pascal's triangle are binomial coefficients. You can calculate them independently for each row:
#include <stdio.h>
#define X 15
int main(void)
{
for (int n = 0; n < X; n)
{
int c = 1;
for (int i = 1;; i)
{
printf("%d\t", c);
if (i > n)
break;
c *= n - i 1;
c /= i;
}
printf("\n");
}
return 0;
}
See: https://en.wikipedia.org/wiki/Pascal's_triangle#Calculating_a_row_or_diagonal_by_itself