w3resource

Java: Accept a number and check the number is even or not


Check Even or Odd

Write a Java program to accept a number and check whether the number is even or not. Prints 1 if the number is even or 0 if odd.

Pictorial Presentation:

Java Basic Exercises: Accept a number and check the number is even or not


Sample Solution:

Java Code:

import java.util.*;

public class Exercise49 {
    public static void main(String[] args) {
        // Create a scanner for user input
        Scanner in = new Scanner(System.in);
        
        // Prompt the user to input a number
        System.out.print("Input a number: ");
        int n = in.nextInt();
        
        // Check if the number is even and print the result
        if (n % 2 == 0) {
            System.out.println(1); // If the number is even, print 1
        } else {
            System.out.println(0); // If the number is odd, print 0
        }
    }
}

Sample Output:

Input a number: 20                                                     
1

Flowchart:

Flowchart: Java exercises: Accept a number and check the number is even or not


For more Practice: Solve these Related Problems:

  • Modify the program to check if a number is prime.
  • Write a program that checks if a number is positive or negative.
  • Modify the program to check if a number is a multiple of another number.
  • Check if a number is even without using modulus (%) operator.

Go to:


PREV : Print Odd Numbers (1-99).
NEXT : Divisible by 3, 5, Both.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.