ในส่วนนี้เราจะดูวิธีตรวจสอบเลขคู่หรือคี่โดยไม่ใช้ conditional statements (<, <=, !=, >, >=, ==)
ปกติตรวจสอบง่ายด้วย conditional statements หาร 2 ดู remainder เป็น 0 หรือไม่ หรือ AND กับ 1 ถ้า 0 เป็น even ไม่ใช่ odd
ที่นี่ไม่ใช้ conditional statements จะแสดง 2 วิธี
Method 1
สร้าง array of strings index 0 เก็บ “Even” index 1 เก็บ “Odd” ส่ง remainder หลังหาร 2 เป็น index เพื่อดึงผลลัพธ์
ตัวอย่างโค้ด
#include<stdio.h> main() { int n; char* arr[2] = {"Even", "Odd"}; printf("Enter a number: "); //take the number from the user scanf("%d", &n); printf("The number is: %s", arr[n%2]); //get the remainder to choose the string }Output 1
Enter a number: 40 The number is: Even
Output 2
Enter a number: 89 The number is: Odd
Method 2
วิธีที่สอง ใช้ tricks logical และ bitwise operators ทำ AND กับ 1 แล้ว logical AND พิมพ์ odd หรือ even ถ้า bitwise AND ผลเป็น 1 logical AND จะคืน odd ไม่เช่นนั้นคืน even
ตัวอย่างโค้ด
#include<stdio.h> main() { int n; char *arr[2] = {"Even", "Odd"}; printf("Enter a number: "); //take the number from the user scanf("%d", &n); (n & 1 && printf("odd"))|| printf("even"); //n & 1 will be 1 when 1 is present at LSb, so it is odd. }Output 1
Enter a number: 40 even
Output 2
Enter a number: 89 odd