Concept Flow - Check if Number is Even or Odd Using Bits
Start with number n
Check least significant bit (n & 1)
Even
Output Even
End
Check the last bit of the number using bitwise AND with 1; if 0, number is even, else odd.
int n = 5; if (n & 1) { printf("Odd\n"); } else { printf("Even\n"); }
| Step | Operation | Number (n) | Bitwise AND (n & 1) | Result | Output |
|---|---|---|---|---|---|
| 1 | Start with number | 5 | |||
| 2 | Calculate n & 1 | 5 | 1 | True (1) | |
| 3 | Check if (n & 1) == 1 | 5 | 1 | Odd | Print "Odd" |
| 4 | End | 5 | Output complete |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| n | 5 | 5 | 5 | 5 |
| n & 1 | 1 | 1 | 1 | |
| Output | Odd | Odd |
Check if number is even or odd using bitwise AND: - Use expression (n & 1) - If result is 0, number is even - If result is 1, number is odd - This checks only the last bit - Faster than modulo (%) operator