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(System.in);
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(System.in); x = in.nextInt(); if ( x % 2 == 0 ) System.out.println("You entered an even number."); else System.out.println("You entered an odd number."); } }
No comments:
Write comments