Java Programs

Even and Odd Program in Java

In this tutorial, we are going to learn writing java program to check a given number is even or odd. For this purpose we will be using if else statement of java concept.

Problem Statement

For any number that is input by the user, we have to check if it is even or odd.

Case1: If the user inputs number 51
then the output should be ‘odd’.
Case2: If the user inputs a number 100.
then the output should be ‘even’.

Our Logic to find Even and Odd Number

  1. Our program will take a number as input from the user.
  2. The input number is checked if it is an even number or not.
  3. If it is, then print ‘even,’ and if it is not, the result should print ‘odd.’

Let’s discuss how to check if a number is an even number.

An integer when divided by ‘2’ and leaves the remainder 0 is called an even number. We can also define an even number as a number that ends with either 0 or 2 or 4 or 6 or 8 is considered an even number.

All the numbers other than even number is considered odd number. Odd numbers always leave the remainder ‘1’ when divided by ‘2’.

Our program divides the input number by ‘2’. If the remainder is ‘0’, we consider a number an even number; otherwise, it is an odd number.

Algorithm to check number is even or odd

Step 1: Start
Step 2: Declare an variable num of integer type.
Step 3: Take an integer input from the user and store it into variable num.
Step 4: if num is divisible by 2
Print ‘even’
else
Print ‘odd’
Step 5: Stop

Even Odd Program in Java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int num;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number to check even or odd ");
        num= sc.nextInt();
        if(num%2 == 0) {
            System.out.println("Given number "+num+" is even");
        } else {
            System.out.println("Given number "+ num +" is odd");
        }
    }
}

Output:

Enter a number to check even or odd 
5
Given number 5 is odd

Explanation

  1. The input integer is 22, which is then checked if it’s divisible by 2.
  2. 5%2 = 0, which is divisible by 2, this makes the integer 22 an even integer.

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs