LearnFrenzy
Sign in Take a free test

Operators and Expressions · Operator Programs · Question 1

Even or odd, positive or negative using operators in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links