Find Even Numbers
In this step, we will see how the modulo operator can be used to check whether a number is even or odd.
- Open the
ModuloOperatorDemo.java
file in a text editor.
- Remove the existing code and replace it with the following code:
public class ModuloOperatorDemo
{
public static void main(String[] args)
{
int[] arr = {7, 5, 2, 4, 6, 19, 18, 25, 22};
for(int i=0; i<arr.length; i++)
{
int num = arr[i];
if((num % 2) == 0)
System.out.println(num + " is even.");
else
System.out.println(num + " is NOT even.");
}
}
}
- Save the file and exit the text editor.
- Compile the code using the command
javac ModuloOperatorDemo.java
.
- Run the code using the command
java ModuloOperatorDemo
.
- The code should output the following:
7 is NOT even.
5 is NOT even.
2 is even.
4 is even.
6 is even.
19 is NOT even.
18 is even.
25 is NOT even.
22 is even.