Pascal's Triangle
C
Easy
7 views
Problem Description
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1 Binomial coefficients. Calculate from previous row to next row: C[i][j] = C[i-1][j-1] + C[i-1][j]
Official Solution
#include <stdio.h>
int main(void)
{
int n = 5;
int C[10][10] = {0};
/* Build Pascal's triangle */
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
/* First and last elements are always 1 */
if (j == 0 || j == i) {
C[i][j] = 1;
} else {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
}
/* Print with proper spacing */
for (int i = 0; i < n; i++) {
/* Leading spaces for centering */
for (int s = 1; s <= n - i; s++) {
printf(" ");
}
for (int j = 0; j <= i; j++) {
printf("%d ", C[i][j]);
}
printf("n");
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!