สามเหลี่ยมฟลอยด์ คือสามเหลี่ยมมุมฉากที่เติมตัวเลขเรียงติดกัน เริ่มจาก 1 ที่มุมซ้ายบน
ตัวอย่าง
1
2 3
4 5 6
7 8 9 10
โปรแกรมที่ 1: พิมพ์สามเหลี่ยมฟลอยด์ปกติ
#include <stdio.h>
int main() {
int rows, i, j, start = 1;
printf("Enter no of rows of Floyd's triangle: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
printf("%d ", start);
start++;
}
printf("\n");
}
return 0;
}
ผลลัพธ์ (rows = 6)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
โปรแกรมที่ 2: พิมพ์สามเหลี่ยมฟลอยด์ย้อนกลับ (Reverse)
#include <stdio.h>
int main() {
int num, i, j;
printf("Enter number of rows: ");
scanf("%d", &num);
int k = num * (num + 1) / 2; // ตัวเลขสุดท้าย
for (i = num; i >= 1; i--) {
for (j = 1; j <= i; j++)
printf("%4d", k--);
printf("\n");
}
return 0;
}
ผลลัพธ์ (rows = 7)
28 27 26 25 24 23 22
21 20 19 18 17 16 15
14 13 12 11 10 9 8
7 6 5 4 3 2 1