In this post we will discuss how to write a program to check whether the number is even or odd in java
first, we understand what Even and Odd is:
Even and Odd:
if a number is evenly divided by 2 (two) without any remainder, then the number is Even. otherwise, the number is odd.
Problem:
Here is example of the problem –
Example 1 :
Input : Enter a number: 7
Output : 7 is an odd number.
Example 2 :
Input : Enter a number: 14 Output : 14 is an even number.
Explanation:
In this example 1, the user entered the number 7
, and the program checked that 7 % 2
is not equal to 0
, indicating that it’s an odd number. and the program then displayed the result.
In example 2, the user entered the number 14
, and the program checked that 14 % 2
is equal to 0
, indicating that it’s an even number and then program print the result.
Solution:
Algorithm to check Number is Even or odd :
- Step 1 – Start the program.
- Step 2 – Read/Input the number.
- Step 3 – if number % 2==0 then the number is Even.
- Step 4 – else number is odd.
- Step 5 – display the output.
- Step 6 – Stop the program.
Approach 1: Even or odd in java using if…….else statement.
class EvenOdd{ public static void main(String[]args){ int n=8; if(n%2==0){ System.out.println("number is even"); } else { System.out.println("number is odd"); } } }
output : number is even.
Approach 2 : Even or Odd program in java using Scanner.
import java.util.Scanner; class EvenOdd{ public static void main(String []args){ //object of scanner class Scanner sc = new Scanner(System.in){ int n; System.out.println("enter the number you want to check"); n =sc.nextInt(); if(n%2==0){ System.out.println(" given number is even"); } else { System.out.println(" given number is odd"); } } } }
Output :
enter the number you want to check 39 given number is odd
more java basic programs:
Addition of two numbers in java
Java Program to Check a Number is Palindrome or Not
Find the Greatest of the Two Numbers in Java