basics · beginner · ~15 min
Use the modulo operator + a conditional to classify an integer.
Decide whether an integer is even, working correctly for negatives too.
Implement int is_even(int n) that returns 1 when n is even and 0 when n is odd. No main — the grader calls it.
One int argument n, anywhere in the int range (positive, negative, or zero).
1 if n is even, 0 if n is odd.
is_even(4) -> 1
is_even(-3) -> 0
is_even(0) -> 1
is_even(-4) -> 1
-4) return 1; watch out that n % 2 can be -1 for negative odd numbers, so compare to 0, not to 1.Modulo is one of the most-used operators in real C code. Get comfortable with it now.
One int argument n.
1 if n is even, 0 if odd.
Negatives must classify correctly: compare n % 2 to 0, not 1.
int is_even(int n) {
/* TODO */
return 0;
}
Missing & on scanf. Capitalising Even/Odd. Checking n % 2 == 1 for odd.
Zero is even. Negatives still classify correctly. Non-integer input → exit non-zero.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.