Java Program to Check Even and Odd Number.

In this program, we will check if the given number is even or odd. To solve this program we must have a basic understanding of if...else statement in Java.


Algorithm for the Java program to check whether a given number is even or odd:

  • Step 1: Start
  • Step 2: Read the input number from the user
  • Step 3: Check if the input number is even or odd:
  • a. If the number is divisible by 2 with no remainder, then it is even
  • b. If the number is not divisible by 2 with a remainder of 1, then it is odd
  • Step 4: Print the result to the console
  • Step 5: End


Java Code Implementation:

import java.util.Scanner;

public class EvenOdd {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = input.nextInt();
        if (num % 2 == 0) {
            System.out.println(num + " is even");
        } else {
            System.out.println(num + " is odd");
        }
    }
}
Output:
Enter a number: 12
12 is even

We use an if-else statement to check whether the num is even or odd. We do this by checking whether num is divisible by 2 using the modulo operator %. If num % 2 is 0, then num is even; otherwise, it is odd.

Finally, we print out the result using the println method of the System.out object.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS