C Program to Check Even or Odd Number
In C, you can check if a number is even or odd by using the modulus operator % like this: if (num % 2 == 0) printf("Even"); else printf("Odd");.
Examples
Input4
Output4 is even
Input7
Output7 is odd
Input0
Output0 is even
How to Think About It
To check if a number is even or odd, divide it by 2 and look at the remainder. If the remainder is 0, the number is even; if it is 1, the number is odd. This uses the modulus operator % which gives the remainder of division.
Algorithm
1
Get input number from the user2
Calculate remainder when number is divided by 23
If remainder is 0, print 'even'4
Otherwise, print 'odd'Code
c
#include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); if (num % 2 == 0) printf("%d is even\n", num); else printf("%d is odd\n", num); return 0; }
Output
Enter an integer: 7
7 is odd
Dry Run
Let's trace the input 7 through the code
1
Input
User enters 7, so num = 7
2
Calculate remainder
7 % 2 = 1
3
Check remainder
Since remainder is 1, condition (num % 2 == 0) is false
4
Print result
Print '7 is odd'
| num | num % 2 | Condition (num % 2 == 0) | Output |
|---|---|---|---|
| 7 | 1 | false | "7 is odd" |
Why This Works
Step 1: Using modulus operator
The % operator gives the remainder of division. Even numbers have zero remainder when divided by 2.
Step 2: Condition check
If remainder is zero, the program prints 'even'; otherwise, it prints 'odd'.
Step 3: Input and output
The program reads an integer from the user and outputs the result accordingly.
Alternative Approaches
Using bitwise AND operator
c
#include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); if ((num & 1) == 0) printf("%d is even\n", num); else printf("%d is odd\n", num); return 0; }
This method uses bitwise AND to check the last bit; it's faster but less intuitive for beginners.
Using ternary operator
c
#include <stdio.h> int main() { int num; printf("Enter an integer: "); scanf("%d", &num); printf("%d is %s\n", num, (num % 2 == 0) ? "even" : "odd"); return 0; }
This method uses a compact ternary operator for concise code.
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a single modulus operation and a conditional check, both constant time operations.
Space Complexity
Only a few variables are used, so space is constant.
Which Approach is Fastest?
Bitwise AND is slightly faster than modulus but both are effectively constant time for this task.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Modulus operator | O(1) | O(1) | Clarity and simplicity |
| Bitwise AND operator | O(1) | O(1) | Performance and low-level operations |
| Ternary operator | O(1) | O(1) | Concise code style |
Use num % 2 == 0 to quickly check if a number is even in C.
Beginners often forget to use % and try to check evenness by dividing and comparing the quotient.