C PROGRAM • DECISION MAKING
Check Whether a Number Is Even or Odd
Use the remainder operator and an if-else decision to classify an integer.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
17
Sample output
Enter an integer: 17 17 is odd.
C PROGRAM
Complete program
#include <stdio.h>
int main(void)
{
int number;
printf("Enter an integer: " );
scanf("%d", &number);
if (number % 2 == 0)
printf("%d is even.\n", number);
else
printf("%d is odd.\n", number);
return 0;
}CURRENT STEP
VARIABLES
| Scope | Name | Value |
|---|---|---|
| Not started | ||
CALL STACK
main()
PROGRAM OUTPUT
Waiting to run…
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read an integer.
- Calculate number % 2.
- If the remainder is zero, print even; otherwise print odd.
An even integer is exactly divisible by 2. Therefore number % 2 gives 0 for even values and a non-zero remainder for odd values.
EFFICIENCY
Time and space complexity
Time complexity
O(1)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Using = instead of == in the condition.
Check this
Using division instead of the remainder operator.
