basics · beginner · ~15 min
Use the modulo operator + a conditional to classify an integer.
Your first real "your turn" exercise after Hello, World. You'll use the modulo operator — the workhorse C uses to check divisibility, walk arrays in circles, hash things, and more.
Write a program that reads one integer from standard input and prints exactly:
even if the number is divisible by 2odd otherwiseint main(void);
A single integer on stdin (positive, negative, or zero).
The literal word even or odd, followed by a newline.
scanf to read the integer. Check that it actually read one.-4 is even, -3 is odd.0 is even.| stdin | stdout |
|---|---|
4 |
even\n |
7 |
odd\n |
0 |
even\n |
-3 |
odd\n |
abc) should make your program exit non-zero. (Easy to do — scanf returns 0 if it didn't read an int.)INT_MIN's sign doesn't matter for parity; INT_MIN % 2 == 0 on every modern platform.% returns the remainder of integer division. n % 2 is 0 for even, 1 (or -1 for negatives) for odd.int n; if (scanf("%d", &n) != 1) return 1; printf("%s\n", n % 2 == 0 ? "even" : "odd"); return 0;if (n % 2 == 1) to detect odd. That's false for -3 on some platforms because -3 % 2 == -1. Compare against zero (even) and treat everything else as odd.& on scanf("%d", &n) (passes the value, not the address — undefined behaviour)."Even" / "Odd" (capitalised). The grader compares case-sensitively.Modulo is one of the most-used operators in real C code. Get comfortable with it now.
One integer on stdin.
even or odd followed by a newline.
Use scanf. Check its return value. Output is exact, lowercase.
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.