ComputerShikshak.com

Java - Even or Odd Number

Problem Statement

Write a program in Java to check whether an integer number entered by the user is Even or Odd.

Brief Description

According to the problem statement we have to write a program in Java that will take an integer value as input from the user through the keyboard and will check whether it is even or odd.

An integer number which is exactly divisible by 2 is an even number otherwise it is odd.

In other words when an integer number is divided by 2 and as remainder 0 is obtained then that is an even number otherwise that is an odd number.

For example, if the user enters 8 as input, the program will generate an output indicating that 8 is an even number. But if the user enters 5 as input, the program will generate an output indicating that 5 is an odd number.

To view Flowchart click the link given below:

Flowchart – Even or Odd Number

Program

				
					import java.util.*;
class EvenOdd
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int num;
        System.out.print("Enter a number: ");
        num=sc.nextInt();
        if(num%2==0)
            System.out.print(num+" is an Even number");
        else
            System.out.print(num+" is an Odd number");
    }
}
				
			

Output 1

Enter a number: 8
8 is an Even number

Output 2

Enter a number: 5
5 is an Odd number

Explanation

In this program:
  • An integer variable namely num is declared.
  • The integer value entered by the user is stored in num.
  • If an even number is entered by the user, the condition num%2==0 is evaluated to true and the statement written within if block is executed to display a message indicating that the entered number is an even number.
  • If an odd number is entered by the user, the condition num%2==0 is evaluated to false and control goes to the else block and the statement written within else block is executed to display a message indicating that the entered number is an odd number. 
When num contains 8, the condition num%2==0 is evaluated to true and the message “8 is an Even number” is displayed. The condition num%2==0  is evaluated as follows:
numnum%2==0
88%2==0
↓
0==0
↓
true
When num contains 5, the condition num%2==0 is evaluated to false and the message “5 is an Odd number” is displayed. The condition num%2==0 is evaluated as follows:
numnum%2==0
55%2==0
↓
1==0
↓
false
Share this page on
Scroll to Top