In this post, we are going to see two ways to print whether a given number is even or odd in Java. First one is using if-else statements, and another one without using if-else statements, using the ternary operator in Java. So, let's dive into the discussion of how to check whether a given number is even or odd.
Step by Step logic of the given Program:
Example 1: Java Program to Check whether a given number is even or odd using If-else statement
import java.util.Scanner;
public class EvenOddNumber
{
public static void main(String[] args) {
//
Scanner sc = new Scanner(System.in);
//Accept input from user
System.out.println("Enter a Number: ");
int num = sc.nextInt();
//Check given number is even or odd
if(num % 2 == 0){
System.out.println("Given Number is Even...");
}else{
System.out.println("Given Number is Odd...");
}
}
}
Enter a Number: 18
Given Number is Even...
Example 2: Java Program to Check whether a given number is even or odd without using If-else statement using ternary operator
In the below program, we are going to use the ternary operator to check whether the given number is even or odd. Since we are using the ternary operator, there is no need to use if-else statements. Here, we are just using the ternary operator to check whether the given number is even or odd. If the number is even, then "Even" will get stored in the result variable, and if the number is odd, then "Odd" will get stored in the result variable. Lastly, we are just printing the value of that result variable.
import java.util.Scanner;
public class EvenOddNumber
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Accept innput from user
System.out.println("Enter a Number: ");
int num = sc.nextInt();
//Checking even-odd using ternary operator
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println("Given Number is "+result);
}
}
Output:Enter a Number: 9
Given Number is Odd
No comments:
Post a Comment
Share your thoughts or ask questions below!...👇