Pascal's Triangle in C
Here's a C program to print Pascal's Triangle:

(图片来源网络,侵删)
#include <stdio.h>
int main() {
int rows, coef = 1, space, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
// Print leading spaces for pyramid shape
for (space = 1; space <= rows - i; space++)
printf(" ");
// Calculate and print each element
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
Explanation:
- Input: The program asks for the number of rows to print.
- Outer Loop: Controls the number of rows.
- Spaces: Prints leading spaces to create the pyramid shape.
- Inner Loop: Calculates and prints each element of the current row.
- The first element of each row is always 1.
- Subsequent elements are calculated using the combination formula: C(i,j) = C(i,j-1) * (i-j+1)/j
- Output: Each row is printed on a new line.
Example Output (for 5 rows):
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Alternative Version (Using 2D Array):
#include <stdio.h>
int main() {
int rows, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
int pascal[rows][rows];
// Fill the array
for (i = 0; i < rows; i++) {
for (j = 0; j <= i; j++) {
if (j == 0 || j == i)
pascal[i][j] = 1;
else
pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
}
}
// Print the triangle
for (i = 0; i < rows; i++) {
// Print leading spaces
for (int space = 1; space <= rows - i; space++)
printf(" ");
for (j = 0; j <= i; j++)
printf("%4d", pascal[i][j]);
printf("\n");
}
return 0;
}
This version uses a 2D array to store the values first, then prints them. It's more memory-efficient for larger triangles as it avoids recalculating values.

(图片来源网络,侵删)
