Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

พิมพ์สามเหลี่ยมปาสกาล (Pascal's Triangle) ด้วยภาษา C

สามเหลี่ยมปาสกาล คือการจัดเรียงจำนวนเต็มเป็นรูปสามเหลี่ยม โดยใช้หลักการคอมบิเนชันและแฟกทอเรียล

การสร้างสามเหลี่ยมปาสกาล

ค่าทุกตำแหน่งนอกสามเหลี่ยมถือเป็น 0 แถวแรกคือ 1 แถวถัดไปได้จากการบวกตัวเลขติดกันของแถวก่อนหน้า

โปรแกรมที่ 1: ใช้ฟังก์ชันแฟกทอเรียล (มีอาร์เรย์)

#include <stdio.h>
int fact(int n) {
    int a, sum = 1;
    for (a = 1; a <= n; a++)
        sum = sum * a;
    return sum;
}
int main() {
    int i, rows, j;
    printf("enter no of rows: ");
    scanf("%d", &rows);
    for (i = 0; i < rows; i++) {
        for (j = 0; j <= (rows - i - 2); j++)
            printf(" ");
        for (j = 0; j <= i; j++)
            printf("%d ", fact(i) / (fact(j) * fact(i - j)));
        printf("\n");
    }
    return 0;
}

ผลลัพธ์ (rows = 5)

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

โปรแกรมที่ 2: ไม่ใช้อาร์เรย์ คำนวณค่าต่อเนื่อง

#include <stdio.h>
int main() {
    int num, row, i;
    printf("Enter the number of rows: ");
    scanf("%d", &num);
    for (row = 1; row <= num; row++) {
        int a = 1;
        for (i = 1; i <= row; i++) {
            printf("%d ", a);
            a = a * (row - i) / i;
        }
        printf("\n");
    }
    return 0;
}

ผลลัพธ์ (rows = 6)

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1