Decision Making Statements** ควบคุมโปรแกรมให้ทำงานตามเงื่อนไข 5 รูปแบบหลัก:
1. Simple if Statement
ทำงานเมื่อเงื่อนไขเป็นจริง (True/Non-zero)
if(condition) {
statement(s);
}
ตัวอย่าง: ตรวจสอบ > 50
#include <stdio.h>
int main() {
int a;
printf("Enter number: ");
scanf("%d", &a);
if(a > 50)
printf("%d is greater than 50\n", a);
return 0;
}
2. if-else Statement
2 ทางเลือก: จริง ทำบล็อกบน, เท็จ ทำบล็อกล่าง
if(condition) {
// True block
} else {
// False block
}
ตัวอย่าง: คี่/คู่
#include <stdio.h>
int main() {
int n;
printf("Enter number: ");
scanf("%d", &n);
if(n % 2 == 0)
printf("%d is Even\n", n);
else
printf("%d is Odd\n", n);
return 0;
}
3. Nested if-else
if ภายใน if/else อีกชั้น
if(cond1) {
if(cond2) stmt1;
else stmt2;
} else {
if(cond3) stmt3;
else stmt4;
}
ตัวอย่าง: หาค่ามากที่สุด 3 ตัว
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter 3 numbers: ");
scanf("%d %d %d", &a, &b, &c);
if(a > b) {
if(a > c)
printf("%d is largest\n", a);
else
printf("%d is largest\n", c);
} else {
if(b > c)
printf("%d is largest\n", b);
else
printf("%d is largest\n", c);
}
return 0;
}
4. Else-if Ladder (หลายเงื่อนไข)
ตรวจสอบเงื่อนไขตามลำดับ จบเมื่อเจอเงื่อนไขจริงตัวแรก
if(cond1) stmt1;
else if(cond2) stmt2;
else if(cond3) stmt3;
...
else stmt_default;
ตัวอย่าง: รากสมการกำลังสอง
#include <stdio.h>
#include <math.h>
int main() {
int a, b, c, d;
float r1, r2;
printf("Enter a b c: ");
scanf("%d %d %d", &a, &b, &c);
d = b*b - 4*a*c; // Discriminant
if(d > 0) {
r1 = (-b + sqrt(d)) / (2*a);
r2 = (-b - sqrt(d)) / (2*a);
printf("Roots: %.2f, %.2f\n", r1, r2);
} else if(d == 0) {
r1 = r2 = -b / (2.0*a);
printf("Equal Roots: %.2f\n", r1);
} else {
printf("Imaginary Roots\n");
}
return 0;
}
5. Switch Statement
เลือกหนึ่งในหลายกรณี ตามค่า Integer/Char Expression
switch(expression) {
case value1: stmt1; break;
case value2: stmt2; break;
...
default: stmt_default;
}
ตัวอย่าง: แปลงตัวเลขเป็นคำ
#include <stdio.h>
int main() {
int n;
printf("Enter number (0-2): ");
scanf("%d", &n);
switch(n) {
case 0: printf("Zero\n"); break;
case 1: printf("One\n"); break;
case 2: printf("Two\n"); break;
default: printf("Wrong choice\n");
}
return 0;
}
ผลลัพธ์
Enter number (0-2): 1 One
ข้อสังเกตสำคัญ Switch
- break สำคัญมาก - ไม่วางจะ "Fall through" ไป case ถัดไป
- Expression ต้องเป็น Integer Type (int, char, enum)
- Case ต้องเป็น Constant Expression
- Default ไม่บังคับ แต่นิยมวางไว้ท้าย
เปรียบเทียบ if-else vs Switch
| ลักษณะ | if-else | Switch |
|---|---|---|
| เงื่อนไข | Boolean Expression ใดๆ | Equality Check เท่านั้น |
| Range Check | ได้ (a > 0 && a < 100) | ไม่ได้โดยตรง |
| Float/Double | ได้ | ไม่ได้ |
| Performance | O(n) ตรวจตามลำดับ | O(1) Jump Table (หลาย case) |
| Readability | เงื่อนไขซับซ้อน | หลายค่าคงที่ชัดเจน |