Selection: CASE · การเลือก: CASE
CASE chooses among values
CASE OFcompares one variable against several values.- It is tidier than many
IFs when each value gives a fixed result. - The block ends at
ENDCASE.
CASE เลือกจากหลายค่า
CASE OFเปรียบเทียบตัวแปรหนึ่งกับหลายค่า- เรียบร้อยกว่าการใช้
IFหลายอันเมื่อแต่ละค่าให้ผลลัพธ์ตายตัว - Block สิ้นสุดที่
ENDCASE
DECLARE Grade : INTEGER
Grade ← 2
CASE OF Grade
1 : OUTPUT "Gold"
2 : OUTPUT "Silver"
3 : OUTPUT "Bronze"
ENDCASE
OTHERWISE catches the rest
OTHERWISEruns when no value matched.- Put it last, just before
ENDCASE.
OTHERWISE ดักจับส่วนที่เหลือ
OTHERWISEรันเมื่อไม่มีค่าใดตรง- วางไว้สุดท้าย ก่อน
ENDCASE
DECLARE Day : INTEGER
Day ← 1
CASE OF Day
1 : OUTPUT "Monday"
2 : OUTPUT "Tuesday"
OTHERWISE OUTPUT "Another day"
ENDCASE
Watch out
- Each branch is written
value : result. The colon:is required. CASEtests equality with set values — useIFfor ranges likeMark >= 50.
ระวัง
- แต่ละสาขาเขียน
value : resultจุด colon:จำเป็นต้องมีการใช้ CASEทดสอบ ความเท่ากัน กับค่าเซต — ใช้IFสำหรับช่วงเช่นMark >= 50
Common mistakes
CASE OF ... OTHERWISE ... ENDCASE;OTHERWISEcatches the rest.- Use CASE when you compare one variable against many values.
ข้อผิดพลาดที่พบบ่อย
CASE OF ... OTHERWISE ... ENDCASE;OTHERWISEดักจับส่วนที่เหลือ- ใช้ CASE เมื่อคุณเปรียบเทียบตัวแปรหนึ่งกับหลายค่า
Now you try
- Read the input, then choose with
CASE OF ... ENDCASE. - Press Check answer to test it.
ลองดูเลย
- อ่านอินพุต แล้วเลือกด้วย
CASE OF ... ENDCASE - กด Check answer เพื่อทดสอบ
Read a Place (an INTEGER). Output Gold for 1, Silver for 2, Bronze for 3, and No medal for anything else. For input 2, output Silver. · อ่าน Place (INTEGER). แสดงผล Gold สำหรับ 1, Silver สำหรับ 2, Bronze สำหรับ 3, และ No medal สำหรับอย่างอื่น สำหรับอินพุต 2, แสดงผล Silver
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Read a CHAR G. Output Excellent for A, Good for B, OK for C, and Try again otherwise. For input B, output Good. · อ่าน CHAR G. แสดงผล Excellent สำหรับ A, Good สำหรับ B, OK สำหรับ C, และ Try again อย่างอื่น สำหรับอินพุต B, แสดงผล Good
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Read an INTEGER N. Output small for 1, medium for 2, and large for anything else. For input 9, output large. · อ่าน INTEGER N. แสดงผล small สำหรับ 1, medium สำหรับ 2, และ large อย่างอื่น สำหรับอินพุต 9, แสดงผล large
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่