Bird
0
0
DSA Cprogramming~5 mins

Check if Number is Even or Odd Using Bits in DSA C - Execution Trace

Choose your learning style9 modes available
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.
Execution Sample
DSA C
int n = 5;
if (n & 1) {
  printf("Odd\n");
} else {
  printf("Even\n");
}
This code checks if the number 5 is even or odd by looking at its last bit.
Execution Table
StepOperationNumber (n)Bitwise AND (n & 1)ResultOutput
1Start with number5
2Calculate n & 151True (1)
3Check if (n & 1) == 151OddPrint "Odd"
4End5Output complete
💡 Bitwise AND result is 1, so number is odd; execution ends after printing.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
n5555
n & 1111
OutputOddOdd
Key Moments - 3 Insights
Why do we use 'n & 1' to check even or odd?
Because the least significant bit (rightmost bit) of an even number is 0, and for odd number is 1. See execution_table step 2 where n & 1 is 1 for number 5.
What if the number is 0? Is it even or odd?
0 & 1 equals 0, so it is even. The check works the same way as shown in execution_table step 2 logic.
Why not use modulo (%) operator instead of bitwise AND?
Bitwise AND is faster and directly checks the last bit, which is enough to determine even or odd. This is shown in the execution_table where only one bit check is done.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'n & 1' at step 2 for number 5?
A5
B0
C1
DUndefined
💡 Hint
Check the 'Bitwise AND (n & 1)' column at step 2 in execution_table.
At which step does the program decide the number is odd?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Result' and 'Output' columns in execution_table to find when odd is printed.
If the number was 4 instead of 5, what would 'n & 1' be at step 2?
A1
B0
C4
DUndefined
💡 Hint
Recall that even numbers have last bit 0; check variable_tracker for 'n & 1' values.
Concept Snapshot
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
Full Transcript
To check if a number is even or odd using bits, we look at its least significant bit. We do this by performing a bitwise AND between the number and 1 (n & 1). If the result is 0, the number is even because its last bit is 0. If the result is 1, the number is odd because its last bit is 1. For example, number 5 in binary ends with 1, so 5 & 1 equals 1, meaning odd. This method is efficient and simple, faster than using modulo. The code prints 'Odd' or 'Even' based on this check. This approach works for all integers including zero, which is even.