The % operator finds the remainder after integer division. A number is even when division by 2 leaves remainder zero. For n = 8, the condition is true and Even is printed. For n = 7, the condition is false and Odd is printed. Zero is even. Negative even numbers also have remainder zero, so the same condition works for them.
Important points
The else branch is optional in a simple if but necessary when a different action is required for a false condition. Place braces around the branches to make their boundaries clear. There is no condition after else. A later statement outside both branches executes after either branch finishes, unless a jump leaves that path.
Time and space complexity
The program uses one remainder calculation and one decision, regardless of the integer value. For the fixed-width integer model used here, time is O(1). Only a fixed number of variables is used, so auxiliary space is O(1).
Flowchart
Explain if-else with a C program to test whether an integer is even or odd. · Download diagram