### do ... while

No. 66

#### Even or odd?

Q:

Write an application which asks for integer values telling its user whether a given value is even or odd. Providing the special value 0 shall terminate your application:

Enter an integer (0 to terminate): 77
77 is an odd number
Enter an integer (0 to terminate): -3
-3 is an odd number
Enter an integer (0 to terminate): 26
26 is an even number
Enter an integer (0 to terminate): 0
0 is an even number
Goodbye!

### Tip

1. Use the modulo % operator.

2. Choose an appropriate loop type with respect to your application's termination on user input «0».

A:

We obviously need a loop to ask for further input unless the last entered value was 0. In any case the loop's statement will be executed at least once:

Enter an integer (0 to terminate): 0
0 is an even number
Goodbye!

A do ... while(...) rather than a while(...) loop is thus appropriate. It allows for entering the loop's body before any check is about to happen:

try(final Scanner scanner = new Scanner(System.in)){

int userInput;
do {
System.out.print("Enter an integer (0 to terminate): ");
userInput = scanner.nextInt();
if (0 == userInput % 2) {
System.out.println("    " + userInput + " is an even number");
} else {
System.out.println("    " + userInput + " is an odd number");
}
} while (0 != userInput);
System.out.println("Goodbye!");
}