If any number is exactly divisible by 2 then itโs an even number else itโs an odd number.
In this tutorial weโll see how to check whether the provided number is even or odd number using Modulo(%).
Flowchart
Flowchart for odd even
Note
- The remainder calculated with
%(Modulo) on dividing by 2, will always be0for all even numbers. - Whereas the remainder on dividing by 2, will always be
1for all odd numbers.
Code
public class OddEven
{
public static void main(String[] args)
{
int a = 58147;
int rem = a % 2;
System.out.println("A : " + a);
System.out.println("Remainder : " + rem);
if( rem == 0)
{
System.out.println( a + " is an even number");
}
else
{
System.out.println( a + " is an odd number");
}
/*
Remainder after dividing by 2
12 % 2 -> 0
13 % 2 -> 1
14 % 2 -> 0
15 % 2 -> 1
16 % 2 -> 0
17 % 2 -> 1
18 % 2 -> 0
19 % 2 -> 1
20 % 2 -> 0
21 % 2 -> 1
22 % 2 -> 0
*/
}
}
Output
58147 is an odd number
Happy ๐ coding
Related Articles
Deepen your understanding with these curated continuations.
How to Find ASCII Value of a Character in Java: 4 Easy Methods
Master finding ASCII values in Java! Explore 4 different methods including type-casting, brute force, and byte arrays with clear, practical code examples.
Factorial of a Number Using For Loop in Java: Code & Algorithm
Find the factorial of any integer in Java using a for loop. Explore the step-by-step logic, code implementation, and why we initialize the result variable to 1.
Factorial of a Number Using While Loop in Java: Guide & Code
Learn how to calculate the factorial of a number in Java using a while loop. This guide includes a step-by-step algorithm, code examples, and output analysis.