Exercise:
Write a Program to check whether an entered number is even or odd.
1.Check using if-else statement.
Click Here to View the Solution!
import java.util.Scanner;
public
class EvenOddChecker{
public static void main(String[] args) {
Scanner reader =
new Scanner(System.in);
System.out.print(
"Enter a number: ");
int number = reader.nextInt();
if(number %
2 ==
0)
System.out.println(number +
" is an even number ");
else
System.out.println(number +
" is an odd number");
}
}
Click Here to View the Output!
Enter a number: 13 13 is an odd number.
Click Here to View the Explanation!
- This program is utilizing the if…else statement for checking that whether the
number
entered is even or odd and displays the result. - Initially, a
number
is entered by the user which is recognized by the program using a scanner object.Reader
, a scanner object is therefore formed which reads the entered number and stores it into a variable of the namenumber
. - Now the
%
operator is used find out that whether the value stored innumber
is even or odd. This operator simply checks that whethernumber
is divisible by 2 or not. - The
if…else
statement is then used for the determination. If the value innumber
is even, that is divisible by 2, the program will print “number
is an even number”. And if the value is odd, that is not divisible by 2, the program will print “number
is an odd number”. - This determination of a number can also be done using a ternary operator which is provided in Java.
2.Check using Ternary Operator.
Click Here to View the Solution!
import java.util.Scanner;
public
class EvenOddChecker {
public static void main(String[] args) {
Scanner reader =
new Scanner(System.in);
System.out.print(
"Enter a number: ");
int number = reader.nextInt();
String evenOdd = (number %
2 ==
0) ?
"even" :
"odd";
System.out.println(number +
" is an " + evenOdd +
" number. " );
}
}
Click Here to View the Output!
Enter a number: 80 80 is an even number.
Click Here to View the Explanation!
- This program finds out that whether the number entered by the user is even or odd using a
ternary operator
and displays the output. - Considering the previous program that used
if…else
statement to perform the same task, this program does the same except that it uses aternary operator (? :)
in place of the if…else statement. - Now, the entered number which is stored in
number
is checked whether it is even or odd. If the value innumber
is divisible by 2, then the term “even” is returned. And if the value is odd, then the term “odd” is returned. Whichever value is returned, it is stored into a string variable by the name evenodd. - Finally, the obtained output is displayed by using the
string concatenation
feature provided by Java.