Java Program to check a given number is even or odd.
Objective
Write a Java program to determine whether a given integer is even or odd.
Algorithm / Approach
- Read a single integer from the user.
- Use the modulo operator to compute
x % 2. - If the remainder is exactly equal to 0, print that the number is EVEN.
- Otherwise, print that the number is ODD.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a Num.: ");
int x = s.nextInt();
if(x%2==0){
System.out.print(x+" IS AN EVEN");
}
else {
System.out.print(x+" IS AN ODD");
}
}
}
Expected Output
Enter a Num.: 20 20 IS AN EVEN
Explanation of the Program
- The modulo operator
%returns the remainder of a division operation. - Dividing any even number by 2 leaves a remainder of 0.
- Dividing any odd number by 2 leaves a remainder of 1.
- The
==operator is used to compare the remainder with 0.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Using the assignment operator
=instead of the equality operator==in the if-condition. - Using division
/instead of modulo%.