Write a program to check whether a number is even or odd

1

In this program you will learn to check whether a given number is even or odd, first program we try to find the number is Even odd program in java using Scanner.

First, understand what is even or odd number if you don't know, a number is said to be:

  • even, if it leaves the remainder as 0 when divided by 2
  • odd, if it leaves the remainder as 1 when divided by 2

Example 1: Even or odd program in Java using if-else

In this approach, we use if ...else control statement that allows checking the condition, our condition will be whether the number is perfectly divisible by 2 or not, it is checked using the modules % operators. If the number is perfectly divisible by two then the number is even otherwise it is odd.


import java.util.Scanner;

public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check even or odd");
int number = scanner.nextInt();

scanner.close();
if(number % 2 == 0)
System.out.println(number + " is even");
else
System.out.println(number + " is odd");
}
}


Output:


Enter a number to check even or odd
4
4 is even



Example 2: Even odd program in java using ternary operator  

Ternary operator is a type of java conditional operator. In this program, we will learn how to use ternary operator instead of if else statemt to find the number is even or odd.

Syntax:


condition ? expression1 : expression2;


In this case the condition will be evaluated and
  • If condtion is true, expression1  is executed.
  • And, If condition is false, expression2  is executed


import java.util.Scanner;

public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to check even or odd");
int number = scanner.nextInt();
scanner.close();
String result = number % 2 == 0 ? "Even" : "Odd" ;
System.out.println(result);
}
}


Output:


Enter a number to check even or odd
7
7 is Odd




Post a Comment

1 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
  1. Starting March 5, 2022, Illinois sports bettors can use any of the live sportsbook apps after online registration 카지노사이트 is first accomplished. Kenya’s status as an early tech adopter helped gasoline the development. New undersea cables and an inflow of Chinese-branded smartphones had drastically decreased value of|the price of} getting online (today an estimated 85% of the population has entry to a connection).

    ReplyDelete
Post a Comment
Our website uses cookies to enhance your experience. Learn More
Accept !