C语言如何实现帕斯卡三角形?

99ANYc3cd6
预计阅读时长 9 分钟
位置: 首页 C语言 正文

Pascal's Triangle in C

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

c语言pascal 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:

  1. Input: The program asks for the number of rows to print.
  2. Outer Loop: Controls the number of rows.
  3. Spaces: Prints leading spaces to create the pyramid shape.
  4. 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
  5. 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.

c语言pascal triangle
(图片来源网络,侵删)
-- 展开阅读全文 --
头像
Linux、Dede、MySQL为何检测不到?
« 上一篇 12-01
织梦dedecms5.7栏目如何添加缩略图?
下一篇 » 12-01

相关文章

取消
微信二维码
支付宝二维码

目录[+]