How to use the C programming language for the Pascal’s Triangle algorithm?
In C language, a two-dimensional array can be used to implement the algorithm for Pascal’s Triangle.
Here is an example code:
#include <stdio.h>
int main() {
int rows, i, j, coef;
printf("输入行数:");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%d ", coef);
}
printf("\n");
}
return 0;
}
Run the example:
输入行数:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
The code uses two nested loops to traverse through each element of Pascal’s Triangle and calculates the value of each element using the combination formula. The first and last elements of each row are both 1, while the values of the other elements are equal to the sum of the elements in the corresponding position from the previous row and the one before that. It uses printf statements to print the value of each element, followed by a newline character at the end of each row.