Default

Java program to find if a number is even or odd?

Java program to find if a number is even or odd?

Even or Odd: If the number is divisible by 2 then it is even, otherwise it is an odd number. On this page, we will write a Java program that checks if a number is odd or even.

Mathematical Definition

The formal mathematical definition of an even number is that it is an integer of the form n = 2i, where i is an integer. An odd number is an integer of the form n = 2i + 1.

even  =   { 2i  such that where i belongs to Z
odd    =   { 2i + 1 such that where i belongs to Z

 

Raptor Flowchart

https://www.testingdocs.com/questions/find-a-number-is-even-or-odd-raptor-flowchart/

 

Even Odd

 

Even or Odd Java program

import java.util.Scanner;

public class EvenOddExample {
 public static void main(String args[])
 {
 System.out.println("Enter number to check if its odd or even");
 Scanner in = new Scanner(System.in);
 int x = in.nextInt();
 if(x % 2 == 0)
 System.out.println("The number is an even number");
 else
 System.out.println("The number is an odd number");

in.close();
 }

}

Output of the program:

Testcase 1

Enter number to check if its odd or even
20
The number is an even number

TestCase2

Enter number to check if its odd or even
77
The number is an odd number

 

Screenshot

EvenOdd Run Output

 

 

We have used the modulus operator to find the remainder in the java program. It is an important arithmetical operator also known as a remainder operator. It returns the remainder of the two numbers. For instance 5 % 2 is 1 because 5 divided by 2 leaves a remainder of 1. In this program, we check for n % 2  is 0 i.e nothing left after dividing the number by 2. So the number is an even number.

 

Modulus operator in Java

 

 

Java Tutorial on this website: