Check whether a number is even or odd using if...else statement
import java.util.Scanner;
public class even1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}
When you run the program, the output will be:
Enter a number: 12
12 is even
BUILD SUCCESSFUL (total time: 6 seconds)
Explanation:-
n the above program, a Scanner object, sc is created to read a number from the user's keyboard. The entered number is then stored in a variable num.
Now, to check whether num is even or odd, we calculate its remainder using % operator and check if it is divisible by 2 or not.
For this, we use if...else statement in Java. If num is divisible by 2, we print num is even. Else, we print num is odd.
import java.util.Scanner;
public class even1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}
When you run the program, the output will be:
Enter a number: 12
12 is even
BUILD SUCCESSFUL (total time: 6 seconds)
Explanation:-
n the above program, a Scanner object, sc is created to read a number from the user's keyboard. The entered number is then stored in a variable num.
Now, to check whether num is even or odd, we calculate its remainder using % operator and check if it is divisible by 2 or not.
For this, we use if...else statement in Java. If num is divisible by 2, we print num is even. Else, we print num is odd.