π§ Problem Statement
Write a Java program to check whether a number is even or odd.
π₯ Input
A number entered by the user, for example:7
π€ Output
A message:7 is an odd number.
π‘ Simple Explanation
Letβs keep it super simple:
- If a number can be divided by 2 without any leftover, itβs called an even number (like 2, 4, 6).
- If thereβs a leftover when dividing by 2, itβs called an odd number (like 1, 3, 5).
We use the % symbol (called the modulus operator) in Java to find out whatβs left over after dividing.
π§Ύ Java Code
import java.util.Scanner;
public class EvenOddCheck {
public static void main(String[] args) {
// Step 1: Take input from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Step 2: Check if number is even or odd
if (number % 2 == 0) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}
}
}
π Step-by-Step (Very Lame Language π)
- We ask the user to enter a number.
- We use
%to check if it divides cleanly by 2. - If
number % 2 == 0, then the number is even. - Otherwise, itβs odd.
- We print the result.
π Example
π User enters: 12
β
Output: 12 is an even number.
π User enters: 9
β
Output: 9 is an odd number.
π― Tiny Challenge for You
Can you figure out whether a number is even or odd without using %?
(Hint: Use division and multiplication π)
π Stay tuned for tomorrowβs challenge!
Like, comment, or share if you’re learning Java with us daily! π