Classifying Numbers | For Loop
Classifying Numbers :
This program reads a given set of integers and then prints the number of odd and even integers. It also outputs 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.
PROBLEM ANALYSIS AND ALGORITHM-DESIGN:
After reading a number, you need to check whether it is even or odd. Suppose the value is stored in number. Divide number by 2 and check the remainder. If the remainder is 0, number is even. Increment the even count and then check whether number is 0. If it is, increment the zero count. If the remainder is not 0, 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 it is 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: 6 % 2 = 0; -4 % 2 = 0; -7 % 2 = -1; 15 % 2 = 1
Repeat the preceding process of analysing 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. Analyse the number.
c. Increment the appropriate count.
2. Print the results.
Main Algorithm:
1. Initialise the variables.
2. Prompt the user to enter 20 numbers.
3. For each number in the list:
a. Read the number.
b. Output the number (echo input).
c. If the number is even:
{
i. Increment the even count.
ii. If the number is zero, increment the zero count.
}
otherwise Increment the odd count.
4. Print the results.
Before writing the C++ program, let us describe Steps 1–4 in greater detail. It will be much easier for you to then write the instructions in C++.
1. Initialise the variables. You can Initialise the variables zeros, evens, and odds when you declare them.
2. Use an output statement to prompt the user to enter 20 numbers.
3. For Step 3, you can use a for loop to process and analyse the 20 numbers. In pseudo code, this step is written as follows:
for (counter = 1; counter <= 20; counter++)
{
read the number;
output number;
switch (number % 2) // check the remainder
{
case 0:
increment even count;
if (number == 0)
increment zero count;
break;
case 1:
increment odd count;
}//end switch
}//end for
4. Print the result. Output the value of the variables zeros, evens,
Comments
Post a Comment