Wednesday, 30 January 2013

Java program to check even or odd

This java program is to check whether a given number is odd or even. The logic is simple where the given number is checked by % of 2 == 0 then say even or odd. Here modulus is a basic arithmetic operator in java.  % modulus can give several meaning with respect to the field. In computer science it is normally refereed as reminder of operands. 

Lets take an example, 10 % 5 = 0 with a remainder of 0 and if we use divide operator it will be 10 / 5 = 2. This is the main logic which we going to use in our java program  The concentration should be on reminder so we check a reminder if it is even or odd. 

The scanner class which allows users to read values of various types in java. To access methods in Scanner class create a new scanner object as "in" by this line 

 Scanner in = new Scanner(;

in the next line is to get an input from the user.

x = in.nextLine(); 

The modulus(%) operator finds the modulus of x with respect to 2 and if it is equal to 0 then say the given number is even or the number is said to be odd.

Check the given below code.

 import java.util.Scanner;  
 class oddeven  
 public static void main(String args[])  
 int x;  
 System.out.println("Enter an integer to check if it is odd or even ");  
 Scanner in = new Scanner(;  
 x = in.nextInt();  
 if ( x % 2 == 0 )  
 System.out.println("You entered an even number.");  
 System.out.println("You entered an odd number.");  

No comments:
Write comments

Featured post

List of Universities in Karnataka offering M.Sc Computer Science

The post-graduate programme in Computer Science (M.Sc Computer Science) contains two academic years duration and having a four semesters....

Popular Posts

Copyright @ 2011-2016