ความหมาย
Else-if ladder เป็นวิธีเขียนเงื่อนไขหลายทางเลือก (multi-way decision) ที่อ่านง่ายและเป็นมาตรฐาน
Syntax
if (condition1) stmt1; else if (condition2) stmt2; ... else if (conditionN) stmtN; else stmtX;
อัลกอริทึม: หาค่าสูงสุดของ 4 ตัวเลข
START
Step 1: ประกาศ int a,b,c,d
Step 2: อ่านค่า a,b,c,d
Step 3: if (a>b && a>c && a>d) print a
else if (b>c && b>a && b>d) print b
else if (c>d && c>a && c>b) print c
else print d
STOPตัวอย่างที่ 1: หาค่าสูงสุดของ 4 ตัวเลข
#include <stdio.h>
int main() {
int a, b, c, d;
printf("ป้อนค่า a,b,c,d: ");
scanf("%d%d%d%d", &a, &b, &c, &d);
if (a > b && a > c && a > d)
printf("%d มากที่สุด\\n", a);
else if (b > c && b > a && b > d)
printf("%d มากที่สุด\\n", b);
else if (c > d && c > a && c > b)
printf("%d มากที่สุด\\n", c);
else
printf("%d มากที่สุด\\n", d);
return 0;
}ผลลัพธ์
Run 1: ป้อนค่า a,b,c,d: 2 4 6 8 8 มากที่สุด Run 2: ป้อนค่า a,b,c,d: 23 12 56 23 56 มากที่สุด
ตัวอย่างที่ 2: Grade Classification
#include <stdio.h>
int main() {
int marks;
printf("ป้อนคะแนน (0-100): ");
scanf("%d", &marks);
if (marks <= 100 && marks >= 90)
printf("Grade = A\\n");
else if (marks < 90 && marks >= 80)
printf("Grade = B\\n");
else if (marks < 80 && marks >= 70)
printf("Grade = C\\n");
else if (marks < 70 && marks >= 60)
printf("Grade = D\\n");
else if (marks < 60 && marks > 50)
printf("Grade = E\\n");
else if (marks == 50)
printf("Grade = F\\n");
else if (marks < 50 && marks >= 0)
printf("Fail\\n");
else
printf("คะแนนไม่ถูกต้อง (0-100)\\n");
return 0;
}ผลลัพธ์ตัวอย่าง
Run 1: ป้อนคะแนน: 78 Grade = C Run 2: ป้อนคะแนน: 98 Grade = A
Else-If Ladder vs Switch
| คุณสมบัติ | Else-If Ladder | Switch |
|---|---|---|
| เงื่อนไข | Relational, logical, range | Equality (discrete values) |
| ประเภทข้อมูล | ทุกประเภท | Integer/char/enum เท่านั้น |
| ประสิทธิภาพ | O(n) ตรวจสอบตามลำดับ | O(1) jump table (มากกว่า ~5 cases) |
| Readability | ดีสำหรับ range conditions | ดีสำหรับค่าคงที่หลายค่า |
Best Practices
- เรียงเงื่อนไขจากเฉพาะเจาะจงไปทั่วไป (specific to general)
- ใช้ braces {} สำหรับ multi-statement blocks
- หลีกเลี่ยง nested else-if ลึกเกินไป (refactor เป็น function)
- พิจารณา lookup table สำหรับ mapping คงที่