For each number, print whether it is even or odd and positive, negative or zero, using only operators (no if).
Solution
main.c
#include <stdio.h>
int main(void) {
int nums[] = {7, -4, 0};
for (int i = 0; i < 3; i++) {
int n = nums[i];
printf("%d: %s, %s\n", n, n % 2 == 0 ? "even" : "odd",
n > 0 ? "positive" : n < 0 ? "negative" : "zero");
}
return 0;
}
Output Verified by compiling and running
7: odd, positive
-4: even, negative
0: even, zero
n % 2 == 0 works for negative numbers too (−4 % 2 is 0, while −3 % 2 is −1, so testing == 1 would be wrong). The chained conditional reads top to bottom like an if-else ladder.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!