Monday, February 11, 2013

Tutorial 10 : If and Else, How to determine the number is even or odd

Java Tutorial For Beginners, Tutorial 9 : If and Else, How to determine the number is even or odd?

Program uses if and else condition. If the number when divided by 2, the remainder is 0 then is an even number. Else the number is an odd number.

Step 1 : Read the number. Use Scanner class to read the input.

Step 2 : Use if and else condition. If number % 2 == 0, then the number is an even number. Else it is an odd number.

Step 3 : Print out the statement.

Code below :


//Program to determine whether a number is even or odd
// Use if else condition
// It is even if the number remainder is 0 when divided by 2
// If the remainder is 1, then the number is odd

//use scanner class for read input

import java.util.Scanner;

public class TestIfTwo{
public static void main(String[] args){
int number = 0;

Scanner myscan = new Scanner(System.in);

//Read input
System.out.print("Enter a number : ");
number = myscan.nextInt();

//if and else condition
if (number % 2 == 0) {System.out.println(number + " is even");}
else {System.out.println(number + " is odd");}

}

}

No comments:

Post a Comment