4. ตัวอย่าง(1) การใช้ If … else
Exsam. การเปรียบเทียบค่าของ a และ b
if(a > b)
printf(“ A > B”);
else
printf(“A < B ”);
อธิบาย.
ถ้า a มีค่ามากกว่า b (ถ้าเงื่อนไขเป็นจริง) ให้พิมพ์ข้อความออกมาว่า “A > B”
แต่ถ้า a ไม่ได้มากกว่า b (เงื่อนไขเป็นเท็จ) ให้พิมพ์ข้อความออกมาว่า A < B
5. ตัวอย่าง(2) การใช้ If … else
Exsam2. การเปรียบเทียบค่าของวัน (จันทร์-อาทิตย์ ) โดยรับข้อมูลจาก
คีย์บอร์ด
if(day == 1)
printf(“number of Monday”);
else
printf(“number of Tuesday”);
อธิบาย
ถ้า ค่าของตัวแปร day มีค่าเท่ากับ 1 จะพิมพ์ข้อความ number of Monday
แต่ถ้า ค่าของตัวแปร day มีค่า ไม่เท่ากับ 1 จะพิมพ์ข้อความ number of Tuesday
6. ตัวอย่าง(3) การใช้ If … else
Exsam3. การเปรียบเทียบค่าของวัน (จันทร์-อาทิตย์ ) โดยรับข้อมูลจากคีย์บอร์ด
if(day == 1)
printf(“number of Monday”);
else if(day == 2)
printf(“number of Tuesday”);
else if(day == 3)
printf(“number of Wednesday”);
else if(day == 4)
printf(“number of Thursday”);
else if(day == 5)
printf(“number of Friday”);
else if(day == 6)
printf(“number of Saturday”);
else if(day == 7)
printf(“number of Sunday”);
else
printf(“number of Wrong !”);
7. #include <stdio.h>
main()
{
int day;
clrscr();
printf("### Day of Week ###n");
printf("Input Number of day: ");
scanf("%d", &day);
if(day == 1)
printf("number of Monday”);
else if(day == 2)
printf("number of Tuesday”); ตัวอย่ างโปรแกรม
else if(day == 3)
printf("number of Wednesday”);
else if(day == 4)
printf("number of Thursday”);
else if(day == 5)
printf("number of Friday”);
else if(day == 6)
printf("number of Saturday”);
else if(day == 7)
printf("number of Sunday”);
else
printf("number of Wrong !”);
getch();
}