Java Reference
In-Depth Information
PROGRAMMING EXAMPLE: Classify Numbers
This program reads a given set of integers and then prints the number of odd integers,
the number of even integers, and the number of zeros.
The program reads 20 integers, but you can easily modify it to read any set of
numbers. In fact, you can modify the program so that it first prompts the user to
specify how many integers are to be read.
Input: 20 integers—positive, negative, or zeros
Output: The number of zeros, even numbers, and odd numbers
5
After reading a number, you need to check whether it is even or odd. Suppose the
value is stored in the variable number . Divide number by 2 and check the remainder.
If the remainder is zero, number is even. Increment the even count and then check
whether number is zero. If it is, increment the zero count. If the remainder is not
zero, increment the odd count.
The program uses a switch statement to decide whether number is odd or even.
Suppose that number is odd. Dividing by 2 gives the remainder 1 if number is
positive, and the remainder -1 if negative. If number is even, dividing by 2 gives the
remainder 0 whether number is positive or negative. You can use the mod operator,
% , to find the remainder. For example:
PROBLEM
ANALYSIS
AND
ALGORITHM
DESIGN
6 % 2 = 0, -4 % 2 = 0, -7 % 2 = -1, 15 % 2 = 1
Repeat the preceding process of analyzing a number for each number in the list.
This discussion translates into the following algorithm:
1. For each number in the list:
a. Get the number.
b. Analyze the number.
c. Increment the appropriate count.
2. Print the results.
Because you want to count the number of zeros, even numbers, and odd numbers,
you need three variables of the type int —say, zeros , evens , and odds —to track
the counts. You also need a variable—say, number —to read and store the number to
be analyzed, and another variable—say, counter —to count the numbers analyzed.
Your program thus needs the following variables:
int counter;
VARIABLES
//loop control variable
int number;
//variable to store the number read
int zeros;
//variable to store the zero count
int evens;
//variable to store the even count
int odds;
//variable to store the odd count
Search WWH ::




Custom Search