Go to Top

Thursday, 24 March 2011

To check whether a number is even or odd

Question 2 : Write a program in Java to check whether a number is even or odd.

The Java program for the question is as follows :

public class even_or_odd
{
 public static void main(int a)
   {
     int b=a%2;
     if (b==0)
     System.out.println("The number "+a+" is an even one");
     else
     System.out.println("The number "+a+" is an odd one");
    }
}

Explanation : Here a number is being taken from the user by passing parameter to the method "main". Then it is checked whether it is even or odd. We know that an even number can be divided by 2 without leaving a  remainder whereas an odd number cannot be divided by 2 without leaving a remainder. It will always leave a remainder. So here we are using an operator known as modulus (symbol "%") which returns the remainder on dividing a number by another. If the mod (in short) of the the number given by the user returns 0, it means that the number is even, but if its mod returns any remainder, it means that it is an odd number.

Input :






















Output :



2 comments:

  1. Exception in thread "main" java.lang.NoSuchMethodError: main
    plz give solution.. what kind of changes will i have to do ?????

    ReplyDelete
  2. Welcome to Ranchi
    Let enjoy and have a great fun.

    ReplyDelete

ShareThis