Week 3 (for codeYourLife only)

profilered357
week_3.zip

chapter 4.docx

Selection Structures: Making Decisions

One of a computer’s characteristic qualities is its ability to make decisions—to select one of several alternative groups of statements. These groups of statements, together with the condition that determines which of them is to be executed, make up a  selection (or decision) control structure. In this chapter, we will discuss the various types of selection structures as well as some of their applications.

After reading this chapter, you will be able to do the following:

· Construct single- and dual-alternative selection structures

· Identify and apply relational and logical operators in program segments

· Use the ASCII coding scheme for associating a number with each character

· Use the relational operators <, !=, ==, <=, >, and >= with arbitrary character strings

· Construct multiple-alternative selection structures

· Use different types of selection structures to solve different programming problems

· Use defensive programming to avoid program crashes, such as division by zero and taking the square root of a negative number

· Identify and write program segments that use menu-driven programs

· Use the built-in square root function in your programs

In the Everyday World Decisions, Decisions, Decisions . . . 

When was the last time you made a decision? A few seconds ago? A few minutes ago? Probably not longer than that because the capability to choose a course of action is a built-in part of being human. It’s a good thing too because it gives us the adaptability we need to survive in an ever-changing world. Examples of decisions you make on a daily basis are plentiful. Some examples are as follows:

· IF it’s the end of the month, THEN pay the rent.

· IF the alarm clock rings, THEN get up.

· IF you’re driving AND it’s nighttime OR it’s raining, THEN turn on the headlights.

· IF the cat is chewing on the furniture, THEN chase him away, OR ELSE give him a treat.

· IF the boss is approaching, THEN resume work, OR ELSE continue playing computer games.

One type of decision is called a  simple decision. A simple decision is both straightforward and limited. The action you take is based on whether a condition is true or false. You won’t feed the dog if you don’t have a dog. However, you may base your decision about what action to take on more than one condition. For example, you will turn on your car headlights if it is nighttime  or if it is raining or if it is nighttime  and raining. The decision to turn on your headlights is based on whether one or both of these two conditions are true. If neither is true, you keep your headlights off.

One of the differences between humans and computers is that the human brain can handle much more complicated decisions and can deal with vague or indefinite outcomes like “maybe” or “a little.”

It is certain that if you didn’t have the ability to make decisions, you probably wouldn’t get very far in this world. And if a computer program was written without any decision-making ability, it would probably be pretty useless. After all, we want computers to solve our problems, and our situations are usually far from simple. For example, if you were writing a payroll processing program for a large company, you would quickly discover that there are many different types of employees. Each worker type (salaried, hourly, temporary) might have his or her pay calculated by a different method. Without writing code to allow the computer to make choices, your program would only be able to process paychecks one way and you would need many different programs to process the payroll. Some would be used for people who worked overtime, some for people who didn’t, some for employees due bonuses, and even more programs for individuals with different tax rates. Not only is this approach tedious and inefficient, but you would also need to employ a person to decide which program to use for each employee. Instead, you can use decisions such as IF the employee worked overtime, THEN add extra pay to create one efficient and flexible program.

Read on—because IF you master the concepts of this chapter, THEN you will open the door to a very powerful programming technique!

4.1 An Introduction to Selection Structures

In this section, we introduce the three basic types of selection structures and discuss two of them in detail. The third type is presented in  Section  4.4 . Selection structures may also be referred to as decision structures—the names are interchangeable.

Types of Selection Structures

A selection structure consists of a  test condition together with one or more groups (or  blocks) of statements. The result of the test determines which of these blocks is executed. The following are the three types of selection structures:

1. A  single-alternative (or  If-Then structure  contains only a single block of statements. If the test condition is met, the statements are executed. If the test condition is not met, the statements are skipped.

2. A  dual-alternative (or  If-Then-Else structure contains two blocks of statements. If the test condition is met, the first block is executed and the program skips over the second block. If the test condition is not met, the first block of statements is skipped and the second block is executed.

3. A  multiple-alternative structure contains more than two blocks of statements. The program is written so that when the test condition is met, the block of statements that goes with that condition is executed and all the other blocks are skipped.

Figures  4.1  and  4.2  show the flow of execution in each of the three types of selection structures. Note that in  Figure  4.1 , the blocks of statements to be executed or skipped are referred to as the  Then and  Else clauses, respectively.

Figure 4.1

Flowcharts for single- and dual-alternative selection structures

Figure 4.2

Flowchart for a multiple-alternative selection structure

Single- and Dual-Alternative Structures

In this section, we will consider single- and dual-alternative selection structures. These are more commonly called If-Then and If-Then-Else structures.

Single-Alternative Structure: The If-Then Structure

The simplest type of selection structure is the If-Then, or single-alternative, structure. The general form of this selection structure is as follows:

If test condition Then

Statement

Statement

.

.

.

Statement

End If

In this pseudocode, the test condition is an expression that is either true or false at the time of execution. For example, if you wanted a robot to answer the door for you, you would program it to open the door when the doorbell rings. The test condition would be “Is the doorbell ringing?” and the block of statements might include “turn the doorknob and pull open the door” and “say hello.” When the doorbell rings, the condition will become true and the robot will execute the statements by turning the doorknob and pulling to open the door and then saying hello. As long as the test condition is not met (the doorbell does not ring), the robot will sit quietly.

If doorbell rings Then

 Turn doorknob and pull door open

 Say hello

End If

In the pseudocode used in this book , we indicate the beginning of a selection structure with an If statement. The end of the structure is indicated by End If. In many programs, a typical test condition is "Is Number equal to 0?" which is true if the value of Number is 0 and is false otherwise. The execution would flow as follows:

· If Number is equal to 0, then the test condition is true and the block of statements between the If statement and the End If statement (the Then clause) is executed.

· If the value of Number is anything else besides 0, then the test condition is false and the block of statements between the If statement and the End Ifstatement is skipped.

In either case, execution proceeds to the program statement following End If.  Example  4.1  provides an illustration of the If-Then structure.

Example 4.1 If You Have Children, Say Yes  . . .  If Not, Say No

Suppose you are writing a program to collect information about employees in a firm. You would like each employee to enter his/her name, address, and other personal data such as marital status, number of children, and so forth. The pseudocode for part of this program might look as follows:

Write "Do you have any children? Type Y for yes, N for no"

Input Response

If Response is "Y" Then

Write "How many?"

Input NumberChildren

End If

Write "Questionnaire is complete. Thank you."

What Happened?

The first two lines of this program segment ask an employee to state whether he has any children. If the response is "yes", the program will ask the next question. If the response is "no", there is no point in asking how many, so this question is skipped. To accomplish this, we use the If-Then structure.

If the test condition (Response is "Y") is true, the Then clause—the statements between If and End If—is executed. If the Response is anything but "Y", the condition is false, the Then clause is skipped, and the next statement executed is the last Write statement in this program segment. The flowchart shown on the left of  Figure  4.1  illustrates this logic.

 Making It Work

You might wonder why this program asks for the specific response of N if the answer is "no" since any response, other than Y will give the same result—the statements inside the If—End If block would still be skipped. Programmers always consider the users when they write programs. In this case, many users would be confused if they were asked to type Y for "yes" and any other key for "no". It makes more sense to the user to type N for "no" if Y is typed for "yes".

 Making It Work

A note about writing test conditions in decision structures: Test conditions can always be written in more than one way. For example, the following program segment gives the same result as the one in  Example  4.1 :

Write "Do you have any children? Type Y for yes, N for no"

Input Response

If Response is not "N" Then

Write "How many?"

Input NumberChildren

End If

Write "Questionnaire is complete. Thank you."

It is up to the programmer to decide how to write a test condition. In many cases, it is simply a matter of personal preference, but in some situations there may be valid reasons for writing a condition in one specific way. In the example shown here, the If clause is executed if the user enters anything  except N. In the original  Example  4.1 , the If clause is executed  only if the user enters Y. Which of these two test conditions do you think is better? Why do you think so? Considerations like this often drive the way a test condition is written.

Dual-Alternative Structure: The If-Then-Else Structure

The If-Then-Else, or dual-alternative, structure has the following general form:

If test condition Then

Statement

.

.

.

Statement

Else

Statement

.

.

.

Statement

End If

Here’s how this structure works.

· If the test condition is true, then the block of statements between the If statement and the word Else (the Then clause) is executed.

· If the test condition is false, then the block of statements between Else and End If (the Else clause) is executed.

In either case, execution proceeds to the program statement following End If.  Example  4.2  provides an illustration of the If-Then-Else structure.

Example 4.2 Profit or Loss: An If-Then-Else Structure

As an example of an If-Then-Else structure, suppose that part of a program is to input the costs incurred and revenue earned from producing and selling a certain product and then display the resulting profit or loss. To do this, we need statements that do the following:

· Compute the difference between revenue and cost, which gives us the profit or loss

· Describe this quantity as a profit if revenue is greater than cost (i.e., if the difference is positive) and as a loss, otherwise

The following pseudocode does the job. The flowchart shown in  Figure  4.3  is the graphical representation of this example.

3

1 Write "Enter total cost:"

2 Input Cost

3 Write "Enter total revenue:"

4 Input Revenue

5 Set Amount = Revenue − Cost

6 If Amount > 0 Then

7 Set Profit = Amount

8 Write "The profit is $" + Profit

9 Else

10 Set Loss = −Amount

11 Write "The loss is $" + Loss

12 End If

What Happened?

The first four statements in this program segment (lines 1–4) prompt for and input the total cost and revenue for the product. We compute the difference between these quantities and store the result in Amount (line 5). The result will be a profit if Amount is a positive number and a loss otherwise. So we want to check to see if the value of Amount is positive, in which case we can proudly display a profit, or if it is negative and we are forced to report a loss. Our test condition, Amount > 0, in the If statement (line 6) is evaluated as follows:

· If this condition is true, the Then clause

· Set Profit = Amount

Write "The profit is $" + Profit

is executed and the profit is displayed.

· If this condition is false, the Else clause

· Set Loss = −Amount

Write "The loss is $" + Loss

is executed.

Why is Loss = −Amount? Loss is set equal to the negative of Amount (so Loss becomes a positive number) and then this amount is displayed. The following examples illustrate what would happen in two instances of input values to this little program:

· If the input values are Cost = 3000 and Revenue = 4000, then Amount = 1000 and the output is as follows: The profit is $1000.

· However, if the input values are Cost = 5000 and Revenue = 2000, then Amount = −3000. The line that sets Loss = −Amount simply changes the sign ofAmount and stores that value (now a positive number) in Loss. If we did not change the sign of Amount, the output would read: The loss is $−3000. A loss is already a negative number so a loss of a negative number would make no sense. By changing the value of Amount from a negative value to a positive value, our output now makes sense: The loss is $3000.

Figure 4.3

Flowchart for profit or loss program shown in  Example  4.2

What would happen if Amount was exactly zero? For example, if the input values are Cost = 3000 and Revenue = 3000, then Amount = 0. In this example, our test condition ensures that there is profit if Amount > 0 and that there is a loss in any other case. But this is clearly not true if Amount = 0 exactly. The display should say something like "You broke even this year." We could deal with this possibility with a multiple-alternative structure. Multiple-alternative structures are discussed later in this chapter.

Format If-Then and If-Then-Else Structures for Easy Readability

To make it easier to read the pseudocode (or code) for an If-Then or If-Then-Else structure, indent the statements that make up the Then andElse clauses. Moreover, in the program code, it is always a good idea to precede the structure with a step comment that explains its purpose.

Self Check for Section 4.1

1. 4.1 Name the three types of selection structures.

2. 4.2 What is the output of code corresponding to the following pseudocode if

a. Amount = 5?

b. Amount = −1?

c. If Amount > 0 Then

d.     Write Amount

e. End If

    Write Amount

3. 4.3 What is the output of code corresponding to the following pseudocode if

a. Amount = 5?

b. Amount = −1?

c. If Amount > 0 Then

d.     Write Amount

e. Else

f.     Set Amount = −Amount

g.     Write Amount

End If

4. 4.4 For the following pseudocode:

5. If Number > 0 Then

6. Write "Yes"

7. End If

8. If Number = 0 Then

9. Write "No"

10. End If

11. If Number < 0 Then

12. Write "No"

End If

a. What is the output of the corresponding code if Number = 10? If Number = −10?

b. Write a single If-Then-Else structure that has the same effect as the given pseudocode.

c. Create a flowchart for the given pseudocode.

4.2 Relational and Logical Operators

As you have seen in  Section  4.1 , decision making involves testing a condition. To help construct these conditions, we use relational and logical operators. In this section, we will discuss these operators.

Relational Operators

Previously, we gave examples of selection structures that included conditions such as Amount < 0 and Amount > 0. The symbols that appear in these conditions are known as  relational operators. There are six standard relational operators, as shown in  Table  4.1 , together with the symbols we use to represent them.

Table 4.1 Relational operators

Operator

Description

<

is less than

<=

is less than or equal to

>

is greater than

>=

is greater than or equal to

==

is equal to (is same as)

!=

is not equal to

A Little More Explanation About Relational Operators

At this point, we should pause and examine these relational operators for a moment. Several of them are clear and uncomplicated, but some of them are either specific to programming or have notation that may be new to you. You are probably familiar with the greater than symbol (>) and the less than symbol (<) from math classes, but the other symbols deserve some comment.

There is no single symbol to represent the concepts  less than or equal to or  greater than or equal to on a keyboard. These concepts are represented by a combination of symbols. That’s why <= represents  less than or equal to and >= represents  greater than or equal to. This notation will be used in pseudocode throughout this text.

Similarly, there is no single symbol to represent the concept  not equal to, so again, a combination of two symbols is used. In this textbook , following the lead of many programming languages, we will use the symbol != to represent the not equal operator.

Finally, special attention needs to be paid to the  equals sign. In programming, there is a distinction between setting one thing equal to the value of another and asking the question, “Is this thing equal to this other thing?” When we assign the value of one variable to something else, we use the equals sign (=). In this case, the equals sign is used as an  assignment operator. When we compare the value of one thing with another, we mean “is the value of the thing on the left the same as the value of the thing on the right?” This is called a  comparison operator. In our pseudocode, as in many programming languages, we use the symbol == (a double equals sign) when comparing the value of a variable with another variable, value, or expression.

 The Comparison Operator versus the Assignment Operator

In pseudocode, when we write Set Variable1 = Variable2, we are actually putting the value of Variable2 into Variable1. For example, if Costcontains the value 50 and SalePrice contains the value 30, after the statement Cost = SalePrice, both Cost and SalePrice will contain the value30. The value of 50 is gone.

However, if we want to check to see if the value of Cost is the same as the value of SalePrice, we use the comparison operator. In some programming languages (as in this textbook’s pseudocode), we would write Cost == SalePrice. To the computer program, this would translate as, “Is the value of Cost the same as the value of SalePrice?” In this case, if Cost is 50 and SalePrice is 30, the answer is no. The two variables, Costand SalePrice retain their initial values.  Note: if you use RAPTOR, refer to  Section  4.7  to see how RAPTOR handles the comparison operator.

This distinction may not have serious consequences as you continue through this text and write pseudocode, but it can wreak havoc on a program when you begin to write a code in a specific programming language. Be aware of this important distinction as you go through the examples.

The relational operators <, >, <=, >=, ==, and != can be used to compare numeric data as well as string data. We will describe how these operators are used with strings in  Section  4.3 Examples 4.3  and  4.4  illustrate the use of relational operators with numbers.

Example 4.3 Using Relational Operators on Numbers

Let Number1 = 3, Number2 = −1, Number3 = 3, and Number4 = 26. Then, all of the following expressions are true:

a. Number1 != Number2

b. Number2 < Number1

c. Number3 == Number1

d. Number2 < Number4

e. Number4 >= Number1

f. Number3 <= Number1

What Happened?

· To see that the conditions in  (a) and  (b) are true, substitute 3 for Number1 and −1 for Number2.

· In  (c), since Number3 has the value of 3 and Number1 has the value of 3, these two variables are the same.

· In (d) it is true that the value of Number2 (−1) is less than 26, the value of Number4.

· Both  (e) and  (f ) are true. Number4 has the value of 26, which is definitely greater than Number1 (3). The relational operator, >=, asks, “is the value ofNumber4 greater than  or equal to the value of Number1?” It is true if  either Number4 is greater than Number1  or if Number4 is the same as Number1. Example (f ) illustrates this; this condition is also true since Number3 and Number1 have the same value.

Example 4.4 Two Ways to Obtain a Positive Result

The program segment below on the right-hand side was obtained from the one on the left by reversing its test condition and its Then and Else clauses. The resulting pseudocode has the same effect as the original.

If Number >= 0 Then

Write Number

Else

Set PositiveNumber = −Number

Write PositiveNumber

End If

If Number < 0 Then

Set PositiveNumber = −Number

Write PositiveNumber

Else

Write Number

End If

What Happened?

What do both these program segments do? In the program segment on the left, the first line asks, “Is Number greater than or equal to zero?” If this condition istrue, then the number is displayed as is. If this condition is not true, then the program continues to the Else clause. If the condition is not true, it means thatNumber must be less than zero (a negative number). The statements that are then executed (the Else clause) change Number (a negative number) to a positive number by setting PositiveNumber equal to the negative of a negative number. Then the new value, a positive number, is displayed.

In the program segment on the right, the first line tests the opposite condition. It asks if Number is negative (less than zero). If this is true, then Number is converted to a positive number in the same way as in the example on the left. If Number is not less than zero, then it can only be either zero or greater than zero. So the program skips to the Else clause and displays the number as is.

Both program segments take a number and display the magnitude (or absolute value) of that number. It does not matter which condition we test for first in this example.

Documentation Is Always Important

Often a program can achieve the desired results in one of several ways. The decision about which code to use is up to you, the programmer. While many of our examples are short and simple, real programs may be much longer and more complicated. Professional programmers often work on code written by other people. It is easier for a programmer to edit someone else’s code if the programmer knows what the segment is designed to do. This is one reason why it is so important to use documentation in the form of comments to explain what your code is doing.

Logical Operators

Logical operators are used to create compound conditions from given simple conditions. This is illustrated in Examples 4.5 and 4.6, which introduce the most important logical operators—OR, AND, and NOT.

Example 4.5 Save Time and Space with the OR Operator

The following program segments are equivalent; each displays the message OK if the number input is either less than 5 or greater than 10. The segment on the right uses the logical operator OR to help perform this task.

Input Number

If Number < 5 Then

Write "OK"

End If

If Number > 10 Then

Write "OK"

End If

Input Number

If (Number < 5) OR (Number > 10) Then

Write "OK"

End If

In the second program segment, the compound condition (Number < 5) OR (Number > 10) is true if either the simple condition, Number < 5 or the other simple condition, Number > 10, is true. It is false if and only if both simple conditions are false.

The AND operator also creates a compound condition from two simple ones. Here, however, the compound condition is true if and only if  both simple conditions are true. For example, the expression (A > B) AND (Response == "Y") is true if and only if A is greater than B  and Response is equal to "Y". If A is not greater than B  or if Response is not equal to "Y", then the compound condition is false.

The NOT operator, unlike OR and AND, acts upon a single given condition. The resulting condition formed by using NOT is true if and only if the given condition isfalse. For example, NOT(A < 6) is true if A is not less than 6; it is false if A is less than 6. Thus, NOT(A < 6) is equivalent to the condition A >= 6.

Example 4.6 Compounding Conditions with Logical Operators

Suppose Number = 1. Is each of the following expressions true or false?

a. ((2 * Number) + 1 == 3) AND (Number > 2)

b. NOT (2 * Number == 0)

· In (a) the first simple condition is true, but the second is false (Number is not greater than 2). Hence, the compound AND condition is false.

· In (b) since 2 * Number = 2, 2 * Number is not equal to 0. Thus, the condition 2 * Number == 0 is false, and the given condition is true.

Truth Tables for the OR, AND, and NOT Operators

The action of the operators OR, AND, and NOT can be summarized by the use of  truth tables  . Let X and Y represent simple conditions. Then for the values of Xand Y given on each line (true or false) on the two leftmost columns of the following table, the resulting truth values of X OR Y, X AND Y, and NOT X are as listed on the right.

Table 4.2 Truth Tables for the OR, AND, and NOT operators

X

Y

X OR Y

X AND Y

NOT X

true

true

true

true

false

true

false

true

false

false

false

true

true

false

true

false

false

false

false

true

Example  4.7  illustrates how logical operators can be useful in programming.

Example 4.7 Working Overtime . . . or Maybe Not

In a certain firm suppose that the following is true:

· Workers who earn less than $10 per hour are paid “time-and-a-half” (i.e., 1.5 times their normal rate of pay) for overtime hours worked.

· Workers who earn $10 or more per hour are paid their regular hourly rate regardless of the number of hours they work.

· In this firm, working more than 40 hours per week is considered overtime.

The following program segment computes a worker’s weekly earnings (TotalPay) based on his or her hourly wage (PayRate) and number of hours worked (Hours).

1 If (PayRate < 10) AND (Hours > 40) Then

2 Set OvertimeHours = Hours − 40

3 Set OvertimePay = OvertimeHours * 1.5 * PayRate

4 Set TotalPay = 40 * PayRate + OvertimePay

5 Else

6 Set TotalPay = Hours * PayRate

7 End If

What Happened?

To see that this program segment works correctly, we need to try it out using sample values as follows:

· Suppose that a worker earns $8 per hour and works 50 hours. Then PayRate = 8 and Hours = 50, so both conditions in the If statement are true, and thus the compound AND condition is true as well. As a result, the Then clause is executed (and the Else clause is skipped), setting the following:

· OvertimeHours = 50 − 40 = 10

· OvertimePay = 10 * 1.5 * 8 = 120

TotalPay = 40 * 8 + 120 = 440

· However, if a worker earns more than $10 per hour or works less than 40 hours per week, then at least one of the conditions in the If statement is false, and thus the compound AND condition is false. In this case, the Then clause is skipped and the Else clause is executed, which computes the employee pay in the usual way, ignoring overtime pay.

Compounding the Compound Condition Issue

As you begin to understand more about programming, you will find that, while each language has specific and strict syntax rules, not every aspect of writing programs is strictly defined. There is almost always more than one way to solve a programming problem. This is especially true when writing compound conditions, as we have seen for conditional statements using relational operators as follows:

10 < 12 is the same as 12 >= 10

6,895 >= 0 is the same as 0 <= 6,895

And the same can be true of compound conditions. For example,

Let A = 1 and let B = 2, then

If A == 1 AND B == 2 Then

Execute Task 1

Else

Execute Task 2

End If

will produce the same result as

If A != 1 OR B != 2 Then

Execute Task 2

Else

Execute Task 1

End If

Example  4.8  demonstrates how we can get the same result as in  Example  4.7 , using an alternate version.

Example 4.8 Overtime or No Overtime, Revisited

In this example, the If statement checks to see if the employee is eligible for overtime pay, as it did in  Example  4.7 . However, this time, if either part of the compound condition is true (i.e., if the employee’s pay rate is greater than $10 per hour or the employee has worked fewer than 40 hours), then a calculation of pay is made without overtime.

This compound condition uses an OR operator. Therefore, the only way it will fail is if both parts are false. This means an employee would have to both make less than $10 per hour and work more than 40 hours. In that case—and only in that case—would the Else clause be executed and pay be calculated with overtime.

From the pseudocode you can see that this accomplishes the same thing as  Example  4.7  but uses a different test condition.

1 If (PayRate >= 10) OR (Hours <= 40) Then

2 Set TotalPay = Hours * PayRate

3 Else

4 Set OvertimeHours = Hours − 40

5 Set OvertimePay = OvertimeHours * 1.5 * PayRate

6 Set TotalPay = 40 * PayRate + OvertimePay

7 End If

Figure  4.4  shows the flowcharts for Examples 4.7 and 4.8. These flowcharts demonstrate how it’s possible to use different compound conditions to accomplish the same programming task.

Figure 4.4

Flowcharts for two versions of the overtime pay calculation problem

Before we move to the next section, we will use  Example  4.7  once more to illustrate the differences and similarities among programming languages. The pseudocode shown in  Example  4.7  will be used to develop true program code for four popular programming languages—C++, Java, Visual Basic, and JavaScript. In all the code samples, the variable names have been kept exactly the same as the pseudocode. It should be noted that different programming languages have specific conventions for variable names, but for the purposes of comparison, and to enable you to see the similarities and differences more clearly, all variable names remain the same here.

 Calculating a Paycheck in C++ and Java

The following code demonstrates the use of the If-Then-Else structure in both C++ and Java. It corresponds to the pseudocode shown in  Example  4.7 . While there are syntactical and other differences between C++ and Java, the code for this program segment is identical. This code segment presumes that the following variables have been declared as floating point numbers (type double in C++ and Java): PayRate, Hours,OvertimeHours, OvertimePay, and TotalPay. It also presumes that values have been input for PayRate and Hours.

1 if(PayRate < 10 && Hours > 40)

2 {

3 OvertimeHours = Hours − 40;

4 OvertimePay = OvertimeHours * (1.5 * PayRate);

5 TotalPay = (40 * PayRate) + OvertimePay;

6 }

7 else

8 {

9 TotalPay = Hours * PayRate;

10 }

The following things can be noted about this C++ and Java code:

· Each executable statement ends with a semicolon

· The symbol for the AND operator is &&

· The compound condition is enclosed in parentheses

 Calculating a Paycheck in Visual Basic

The following code demonstrates the use of the If-Then-Else structure in Visual Basic. It corresponds to the pseudocode shown in  Example  4.7 . This code segment presumes that the following variables have been declared as floating point numbers (type single in Visual Basic): PayRate,Hours, OvertimeHours, OvertimePay, and TotalPay. It also presumes that values have been input for PayRate and Hours.

1 If PayRate < 10 AND Hours > 40 Then

2 OvertimeHours = Hours − 40

3 OvertimePay = OvertimeHours * 1.5 * PayRate

4 TotalPay = 40 * PayRate + OvertimePay

5 Else

6 TotalPay = Hours * PayRate

7 End If

The following things can be noted about this Visual Basic code:

· Semicolons are not needed at the end of executable statements.

· The If-Then-Else structure must have an End If statement.

· The compound condition does not need to be enclosed in parentheses.

 Calculating a Paycheck in JavaScript

The following code demonstrates the use of the If-Then-Else structure in JavaScript. It would probably be called from a web page and the results displayed on the web page. It corresponds to the pseudocode shown in  Example  4.7 . This code segment presumes that the following variables have been declared as floating point numbers, which require the use of the parseFloat() JavaScript function (not shown): PayRate, Hours,OvertimeHours, OvertimePay, and TotalPay. It also presumes that values have been input for PayRate and Hours.

1 if(PayRate < 10 && Hours > 40)

2 {

3 OvertimeHours = Hours − 40;

4 OvertimePay = OvertimeHours * (1.5 * PayRate);

5 TotalPay = (40 * PayRate) + OvertimePay;

6 }

7 else

8 {

9 TotalPay = Hours * PayRate;

10 }

You may note that this code is virtually identical to both C++ and Java. The differences would become apparent when each code snippet is utilized in a larger program. The JavaScript code would probably be executed by clicking on a button on a web page. You may also notice that Visual Basic code is the most different from the other three. JavaScript, Java, and C++ descended from the same original language, while Visual Basic was developed independently.

Hierarchy of Operations

In a single given condition, there may be arithmetic, relational, and logical operators. If parentheses are present, we perform the operations within parentheses first. In the absence of parentheses, the arithmetic operations are done first (in their usual order), then any relational operation, and finally, NOT, AND, and OR, in that order. This hierarchy of operations is summarized in  Table  4.3  and is illustrated in  Example  4.9 .

Table 4.3 Hierarchy of order of operations

Description

Symbol

Arithmetic Operators are evaluated first in the order listed

First: Parentheses

( )

Second: Exponents

^

Third: Multiplication/Division/Modulus

*, /, %

Fourth: Addition/Subtraction

+ −

Relational Operators are evaluated second, and all relational operators have the same precedence

Less than

<

Less than or equal to

<=

Greater than

>

Greater than or equal to

>=

The same as, equal to

==

Not the same as

!=

Logical Operators are evaluated last in the order listed

First: NOT

! or NOT or not

Second: AND

&& or AND or and

Third: OR

|| or OR or or

More Symbols

In this text, we will use the short words, OR, AND, and NOT to represent the three logical operators. However, some programming languages use symbols to represent these operators. The corresponding symbols are shown in  Table  4.3 .

Example 4.9 Combining Logical and Relational Operators

Let Q = 3 and let R = 5. Is the following expression true or false?

NOT Q > 3 OR R < 3 AND Q − R <= 0

Keeping in mind the hierarchy of operations, in particular, the fact that among logical operators, NOT is performed first, AND is second, and OR is last, let’s insert parentheses to explicitly show the order in which the operations are to be performed:

(NOT(Q > 3)) OR ((R < 3) AND ((Q − R) <= 0))

We evaluate the simple conditions first and find that Q > 3 is false, R < 3 is false, and (Q − R) <= 0 is true. Then, by substituting these values (true orfalse) into the given expression and performing the logical operations, we arrive at the answer. We can show this is by means of an evaluation chart as follows:

Given:

(NOT(Q > 3))

OR

((R < 3)

AND

((Q − R) <= 0))

Step 1:

(NOT(false))

OR

((false)

AND

(true))

Step 2:

(true)

OR

(false)

Step 3:

true

Thus, the given relational expression is true.

 The Boolean Type

Most programming languages allow variables to be of logical (also called Boolean) type. Such a variable may only take one of two values, true orfalse. For example, we can declare a variable, say Answer, to be of Boolean type and then use it in a statement anywhere that a value of true orfalse is valid, such as the following C++ snippet:

bool Answer;

Answer = true;

if(Answer) cout << "Congratulations!";

This statement means: If the value of Answer is true, then write "Congratulations!" on the screen. The following C++ statement is equivalent to the if statement shown above and may be clearer:

if (Answer == "true") cout << "Congratulations!";

Self Check for Section 4.2

1. 4.5 Replace the blank by one of the words:  arithmetic,  relational, or  logical.

a. <= is a(n)            ____________ operator.

b. + is a(n)            ____________ operator.

c. OR is a(n)            ____________ operator.

2. 4.6 Indicate whether each of the following expressions is true or false.

a. 8 <= 8

b. 8 != 8

3. 4.7 Indicate whether each of the following expressions is true or false.

a. 8 = 9 OR 8 < 9

b. 3 < 5 AND 5 > 7

c. 4 != 6 AND 4 != 7

d. 6 == 6 OR 6 != 6

4. 4.8 Let X = 1 and let Y = 2. Indicate whether each of the following expressions is true or false

a. X >= X OR Y >= X

b. X > X AND Y > X

c.  X > Y OR X > 0 AND Y < 0

d. NOT(NOT X == 0 AND NOT Y == 0)

5. 4.9 Write a program segment that inputs a number Number and displays the word Correct if Number is between 0 and 100. This means Number must be both greater than 0 and less than 100.

4.3 ASCII Code and Comparing Strings

In  Chapter  1 , we loosely defined a character as any symbol that can be typed on the keyboard. These symbols include special characters like asterisks (*), ampersands (&), @ signs and the like, as well as letters, digits, punctuation marks, and blank spaces. In this section, we give a more precise definition of a character and discuss how characters are represented in a computer’s memory. We also describe how the relational operators <, <=, >, !=,==, and >= can be applied to any string of characters.

Representing Characters With Numbers

Strictly speaking, a  character is any symbol that is recognized as valid by the programming language you are using. Consequently, what constitutes a character varies from language to language. Nevertheless, most programming languages recognize a common core of about 100 basic characters including all those that can be typed on the keyboard.

All data, including characters, are stored in the computer’s memory in a binary form—as bit patterns; that is, as sequences of zeros and ones. Thus, to make use of character and string variables, a programming language must use a scheme to associate each character with a number. The standard correspondence for a basic set of 128 characters is given by the  American Standard Code for Information Interchange  (  ASCII code  ). The acronym ASCII is pronounced “askey.”

Under this coding scheme, each character is associated with a number from 0 to 127. For example, the uppercase (capital) letters have ASCII codes from 65 ("A") to 90 ("Z"); the digits have codes from 48 ("0") to 57 ("9"), and the ASCII code for the blank (the character that results from pressing the keyboard’s spacebar) is32.  Table  4.4  lists the characters corresponding to ASCII codes from 32 to 127; codes 0 to 31 represent special symbols or actions, such as sounding a beep (ASCII 7) or issuing a carriage return (ASCII 13) and are not shown here.

Thus, to store a character string in the computer’s internal memory, the programming language software can simply place the ASCII codes for its individual characters in successive memory locations. For example, when program code corresponding to the following pseudocode:

Set Name = "Sam"

is executed, the ASCII codes for S, a, and m (83, 97, and 109, respectively) are stored in consecutive memory locations. These numbers, as you recall, are stored in binary, as a series of zeros and ones. Each location uses 1 byte—8 bits—of memory. Then, when the string variable Name is referenced in the program, the programming language interprets the memory contents as ASCII codes and displays the string properly.

Table 4.4 The ASCII codes from 32 to 127

Code

Character

Code

Character

Code

Character

Code

Character

Code

Character

Code

Character

32

[blank]

48

0

64

@

80

P

96

`

112

p

33

!

49

1

65

A

81

Q

97

a

113

q

34

"

50

2

66

B

82

R

98

b

114

r

35

#

51

3

67

C

83

S

99

c

115

s

36

$

52

4

68

D

84

T

100

d

116

t

37

%

53

5

69

E

85

U

101

e

117

u

38

&

54

6

70

F

86

V

102

f

118

v

39

'

55

7

71

G

87

W

103

g

119

w

40

(

56

8

72

H

88

X

104

h

120

x

41

)

57

9

73

I

89

Y

105

i

121

y

42

*

58

:

74

J

90

Z

106

j

122

z

43

+

59

;

75

K

91

[

107

k

123

{

44

,

60

<

76

L

92

\

108

l

124

|

45

61

=

77

M

93

]

109

m

125

}

46

.

62

>

78

N

94

ˆ

110

n

126

47

/

63

?

79

O

95

_

111

o

127

[delete]

Consider the string "31.5" and the floating point number 31.5. These expressions look similar, but from a programming standpoint they are quite different.

· The number 31.5 is stored in memory as the binary equivalent of 31.5. Moreover, since it is a number, it can be added to, subtracted from, divided by, or multiplied by another number.

· The string "31.5" is stored in memory by placing the ASCII codes for 3, 1, ., and 5 in consecutive storage locations. Since "31.5" is a string, we cannot perform arithmetic operations on it, but we can concatenate it with another string.

Now you understand why it is necessary to declare a variable with a data type!

Ordering Arbitrary Strings

We have seen how to use the relational operators, equal to (==) and not equal to (!=). With the aid of the ASCII code, all six relational operators may be applied to arbitrary strings of characters.

Notice that we can order the set of characters based on the numerical order of their ASCII codes. For example, "*" < "3" because the ASCII codes for these characters are 42 and 51, and 42 < 51, respectively. Similarly, "8" < "h" and "A" > " " (the blank). Therefore, under the ASCII code ordering, the following is true:

· Letters are in alphabetical order and all uppercase letters precede all lowercase letters.

· Digits (viewed as characters) retain their natural order. For example, "1" < "2", "2" < "3", and so forth.

· The blank precedes all digits and letters.

Examples 4.10  and  4.11  illustrate how ASCII codes are used to compare string data.

Example 4.10 Comparing Characters

All of the following conditions are true:

a. "a" > "B"

b. "1" <= "}"

c. "1" >= ")"

To check that each condition holds, just find the ASCII codes for the two characters involved ( Table  4.4 ) and verify that the ASCII codes are in the proper order.

Two strings, S1 and S2, are equal (S1 == S2) if they have exactly the same characters in exactly the same order; they are not equal (S1 != S2) otherwise. To determine which of the two unequal strings comes first, use the following procedure:

1. Scan the strings from left to right, stopping at the first position for which the corresponding characters differ or when one of the strings ends.

2. If two corresponding characters differ before either string ends, the ordering of these characters determines the ordering of the given strings.

3. If one string ends before any pair of corresponding characters differ, then the shorter string precedes the longer one.

When applying this procedure, the following is true:

· If string S1 precedes string S2, then S1 < S2.

· If string S1 follows string S2, then S1 > S2.

Example 4.11 True (or False ) Comparisons

Is each of the following expressions true or false?

a. "Word" != "word"

b. "Ann" == "Ann "

c. "*?/!" < "*?,3"

d. "Ann" <= "Anne"

· In (a) the two strings do not consist of the same characters. The first contains an uppercase W, which is a different character from the lowercase w. Hence, the strings are not equal, and this expression is true.

· In (b) again the strings do not consist of the same characters. The second string contains a blank at the end, while the first does not. Hence, this expression is false.

· For (c) the first pair of characters that differ occurs in the third position. Since "/" has ASCII code 47 and "," has code 44, the first string is greater than the second. Therefore, this expression is false.

· For (d) the first string ends before any pair of characters differ. Hence, the first string is less than the second, and this expression is true.

Beware of Strings of Digits

A character string may consist solely of digits, say "123", in which case it looks like a number. However, "123" is  not the same as 123. The first is a string constant, while the second is a numeric constant. Remember: The numeric constant is stored in memory by storing the binary equivalent of123, but the string constant is stored in memory by successively storing the ASCII codes for 1, 2, and 3. Moreover, since we have no mechanism for comparing numbers with strings, if the variable (Num) is a numeric variable, statements like the following:

Num == "123"

make no sense and will lead to an error message if used in a program.

There is another, more subtle, problem that occurs when we compare strings of digits. Following the procedure given above for ordering strings, we see that the following statements:

"123" < "25" and "24.0" != "24"

are true statements (check for yourself!), even though, on the surface, neither inequality seems reasonable.

Self Check for Section 4.3

1. 4.10 Indicate whether each of the following statements is true or false.

a. Two characters are equal if their ASCII codes are equal.

b. If string A is longer than string B, then A is always greater than B.

2. 4.11 Indicate whether each of the following statements is true or false.

a. "m" <= "M"

b. "*" > "?"

3. 4.12 Indicate whether each of the following statements is true or false.

a. "John" < "John "

b. "???" <= "??"

4. 4.13 Write a program segment that inputs two strings and displays the one that comes first under the ASCII code ordering.

4.4 Selecting from Several Alternatives

The If-Then-Else (dual-alternative) structure selects, based on the value of its test condition, one of the two alternative blocks of statements. Sometimes, however, a program must handle decisions having more than two options. In these cases, we use a multiple-alternative selection structure. As you will see, this structure can be implemented in several different ways. To contrast the different methods, we will use each method to solve the same problem. The problem involves a selection structure with four alternatives.

Imagine that you were recently hired as a Mystery Shopper and your task is to rate products. You test each product and assign it a score, from 1 to 10, based on your opinion of the product. But the report you are required to submit to your employer states that you must give each product a letter grade. So you decide to develop a program that will change your number rating into a letter grade and will display the new ratings. We will write a program segment that translates your numerical score (an integer from 1 to 10) into a letter grade according to the following rules:

· If the score is 10, the rating is “A.”

· If the score is 8 or 9, the rating is “B.”

· If the score is 6 or 7, the rating is “C.”

· If the score is below 6, the rating is “D.”

Using If Structures

You could implement a multiple-alternative structure by using several applications of If-Then or If-Then-Else statements. The simplest technique makes use of a sequence of If-Then statements in which each test condition corresponds to one of the alternatives.  Example  4.12  illustrates this technique.

Example 4.12 Assigning Ratings—the Long Way

1 Declare Score As Integer

2 Declare Rating As Character

3 Write "Enter score: "

4 Input Score

5 If Score == 10 Then

6 Set Rating = "A"

7 End If

8 If (Score == 8) OR (Score == 9) Then

9 Set Rating = "B"

10 End If

11 If (Score == 6) OR (Score == 7) Then

12 Set Rating = "C"

13 End If

14 If (Score >= 1) AND (Score <= 5) Then

15 Set Rating = "D"

16 End If

This technique is straightforward and involves pseudocode (and corresponding program code) that is easy to understand. However, it is tedious to write and isinefficient. Regardless of the value of Score, the program must evaluate all four test conditions.  Figure  4.5  contains a flowchart showing the flow of execution in this example.

Figure 4.5

Using a sequence of If-Then statements

Another way to implement a multiple-alternative structure is to  nest If-Then-Else structures. When one structure is nested in another, this means the entire inner structure occurs within an outer structure. This technique is illustrated in  Example  4.13 .

Example 4.13 Assigning Ratings, the Nested If-Then-Else Way

This program segment uses nested If-Then-Else structures to solve the rating assignment problem. Although the resulting code will be more efficient than that shown in  Example  4.12 , it’s still long and tedious and is also more difficult to follow. The flowchart shown in  Figure  4.6  should help you untangle the flow of execution in the following pseudocode:

1 Declare Score As Integer

2 Declare Rating As Character

3 Write "Enter score: "

4 Input Score

5 If Score == 10 Then

6 Set Rating = "A"

7 Else

8 If (Score == 8) OR (Score == 9) Then2

9 Set Rating = "B"

10 Else

11 If (Score == 6) OR (Score == 7) Then

12 Set Rating = "C"

13 Else

14 Set Rating = "D"

15 End If

16 End If

17 End If

Figure 4.6

Using a nested If-Then-Else structure

What Happened?

Let’s take a test value of Score and see how this pseudocode works. You have just tried out a new coffee pot and given it a rating of 8. The value of Score is now equal to 8. Since Score is not 10, the first statement (Set Rating = "A") is skipped and the first Else clause is executed. The test condition (Score == 8) OR (Score == 9) is evaluated and found to be true. Thus, the Then clause of this particular structure is executed, Rating is set equal to "B", the next twoElse clauses are skipped, and execution of all If-Then-Else structures is complete. Notice that unlike the technique used in  Example  4.12 , this program does not always have to evaluate all test conditions to accomplish the rating assignment.

Using Case-Like Statements

So far, we have demonstrated two ways (both using If structures) to create a multiple-alternative selection structure. To make it easier to code multiple-alternative structures, many programming languages contain a statement, usually called  Case or Switch, specifically designed for this purpose. This statement contains a single test expression that determines which block of code is to be executed. A typical Case statement looks as follows:

Select Case Of test expression to be evaluated

Case 1st value:

Statements

Break out of Cases

Case 2nd value:

Statements

Break out of Cases

Case 3rd value:

Statements

Break out of Cases

.

. All the rest of the values that can be chosen

.

Case nth value:

Statements

Break out of Cases

Default:

Statements to execute if test expression does not match any of the above

End Case

The Action of a Case Statement

Here’s how this statement works: The test expression is evaluated and its value is compared with the first Case value. If there is a match, the first block of statements is executed and the structure is exited. If there is no match, the value of the test expression is compared with the second value. If there is a match here, the second block of statements is executed and the structure is exited. This process continues until either a match for the test expression value is found or until the end of the Cases is encountered. The programmer can either write a Default statement—something that will happen if the test expression does not match with any of the Cases, or the programmer can allow no action to be taken. After either the Default or the end of all the Cases, the structure is exited. The Case statement works only when the test expression is an integer or a single character. Use of the Case statement is illustrated in Examples 4.14 and 4.15.

Example 4.14 Assigning Ratings, Using a Case Statement

Let’s return to the rating assignment problem. Here is the third solution. The flowchart shown in  Figure  4.7  shows the flow of the Case structure, as used in this program segment.

1 Declare Score As Integer

2 Declare Rating As Character

3 Write "Enter score: "

4 Input Score

5 Select Case Of Score

6 Case 10:

7 Set Rating = "A"

8 Break

9 Case 9:

10 Case 8:

11 Set Rating = "B"

12 Break

13 Case 7:

14 Case 6:

15 Set Rating = "C"

16 Break

17 Case 5:

18 Case 4:

19 Case 3:

20 Case 2:

21 Case 1:

22 Set Rating = "D"

23 Break

24 End Case

25 Write Rating

What Happened?

When this Case statement is executed, Score is evaluated and the Cases are examined. If a constant equal to Score is found in one of the Cases, the corresponding statement is executed. To see what happens in the Case structure more clearly, let’s walk a test value through the program. As a Mystery Shopper, you have been asked to rate a new style of backpack. The quality of the material and the size of the backpack are wonderful, but the straps hurt your shoulders so you give it a Score of 7. The following happens:

· Line 5 says that the value of the variable (Score) will be compared to the values listed in the cases.

· Line 6 compares Score to the value of 10; because Score is not 10, the program jumps over lines 7 and 8 to line 9.

· Line 9 checks to see if Score has the value of 9; because Score is not 9, the program proceeds to line 10. Since Score is not 8, the program jumps to line 13.

· Line 13 checks to see if Score has the value of 7; because Score is 7, the program continues to execute every statement until a Break is encountered.

· Nothing happens on line 14 but line 15 sets the value of (Rating)to "C".

· Line 16 is a command to break out of the Cases. If a Break statement is not included at the end of each Case, all the subsequent Cases will be executed—often with unfortunate results.

· Because a match has been found in one of the Cases and a Break statement has been executed, the program skips lines 17–23 and jumps to line 24, the end of the Case structure; execution proceeds to line 25 and the value of Rating is displayed—i.e., a C displays.

Figure 4.7

Flowchart for the Case structure

What would happen in  Example  4.14  if the value of Score was 12? Or 0? In both instances, the Case structure would never find a match forScore. But the program would still get to line 25, which says to display the value of Rating. So whatever value had been previously stored in the variable Rating would be displayed. This could be an A from a previous product that you rated, a D, or gibberish from the computer’s storage area. It is a good idea to have a default message coded in your program for this possibility. For example, you might put in a Default statement before the End Case statement that would store a nonexistent rating value such as "Z" in the variable Rating in case a value outside the range of 1–10 was entered or you could have a default display message that might say "No rating available".

Example 4.15 A Fortunate Use of the Case Statement

Now that you are starting to write programs, you need to use your skill to create something that can be enjoyed by others. You decide to write a fortune-telling program for children at a local after-school care center. The child can enter a number (perhaps his or her age or a favorite number) and the program will deliver the child’s fortune. In order for this game to be interesting, there must be a lot of possible fortunes. But using If-Then-Else clauses would make coding extremely long and tedious. This situation is ideal for the Case statement.

For the purposes of this example, we will only display five fortunes but, once you study the pseudocode, you will see that it is a simple matter to add another fivefortunes, or 10, or 100, or as many as you like. Also, when the game becomes stale (i.e., the children have seen each fortune several times), it is easy to change the fortunes. The pseudocode for the fortune teller program is as follows:

1 Declare Fortune As Integer

2 Write "Enter your favorite whole number between 1 and 5:"

3 Input Fortune

4 Select Case of Fortune

5 Case 1:

6 Write "You will get a lot of money soon."

7 Break

8 Case 2:

9 Write "You will marry your one true love."

10 Break

11 Case 3:

12 Write "Study hard! There might be a quiz tomorrow."

13 Break

14 Case 4:

15 Write "Be kind to your teacher."

16 Break

17 Case 5:

18 Write "Someday you will become a game master."

19 Break

20 Default:

21 Write "You entered an invalid number."

22 End Case

What Happened?

In this example, the user enters a number that is stored in the integer variable, Fortune. That value is then compared with the number in each Case until a match is found. When a match is found, the corresponding Write statement is executed and the fortune is displayed. If the user enters a number that is not in the requested range, no match is found and the Default value—the message that the entry is invalid—is displayed.

The value of the Case statement is clear from this example. The fortunes can be changed easily, and more fortunes can be added with only one change in the code: the range of values requested needs to be updated.

Self Check for Section 4.4

1. 4.14 Using each method indicated, construct a multiple-alternative structure that displays "Low" if X is equal to 0, "Medium" if X is equal to 1 or 2, or "High" if X is greater than 2 but less than or equal to 10. Assume that X is an integer. Be careful to distinguish between comparisons, using the comparison operator (==), and assignments, using the assignment operator (=).

a. Use a sequence of If-Then statements.

b. Use nested If-Then-Else statements.

c. Use a Case statement.

2. 4.15 Suppose Choice is a variable of Character type. Write pseudocode for a multiple-alternative structure that tells the program to do one of three things, specified as follows:

. Do YesAction if Choice is "y" or "Y"

. Do NoAction if Choice is "n" or "N"

. If Choice is any other character, display the message "Signing off! Byebye."

4.5 Applications of Selection Structures

In this section, we discuss two important applications of selection structures: defensive programming and menu-driven programming.

Defensive Programming

Defensive programming involves the inclusion of statements within a program to check for improper data during execution. The program segment that catches and reports an error of this sort is called an  error trap. In this section, we will show how to prevent two common “illegal operations”—division by 0 and taking the square root of a negative number. ( Chapter  5  presents another aspect of defensive programming—data validation—checking that input data are in the proper range.)

Avoiding Division by Zero

If a division operation is performed during execution of a program and the number being divided by (the divisor) is 0, execution will halt and an error message will be displayed. In such a situation, we say that the program has  crashed.  Example  4.16  illustrates how to program defensively against this type of error with the aid of an If-Then-Else selection structure.

Example 4.16 Displaying the Reciprocal of a Number

The reciprocal of a number is just 1 divided by that number. Thus, the reciprocal of 8 is 1/8, and the reciprocal of 2/3 is 1/(2/3) = 3/2. Notice that to get the reciprocal of a fraction, we just flip it—interchange its numerator and denominator. Every number, except 0, has a reciprocal. We say that the reciprocal of 0  is not defined because there is no real number equal to 1/0. The following program segment displays the reciprocal of the number entered by the user unless that number is 0, in which case it displays an appropriate message.

1 Write "Enter a number."

2 Write "This program will display its reciprocal."

3 Input Number

4 If Number != 0 Then

5 Set Reciprocal = 1/ Number

6 Write "The reciprocal of " + Number + " is " + Reciprocal

7 Else

8 Write "The reciprocal of 0 is not defined."

9 End If

In this program segment, the Else clause is the error trap. An error trap anticipates and checks for a value that would cause a problem in the running of the program. This error trap handles the possibility of a request for division by zero. By anticipating this illegal operation, we prevent the program from crashing.

 Computers Don’t Know Everything: Be Sure Your Display Is What  You Want

If you enter the number 5 in  Example  4.16 , the reciprocal is 1/5. However, the line

Set Reciprocal = 1/Number

will set the value of the reciprocal to the mathematical value of 1 ÷ 5, which is 0.2. The display will say

The reciprocal of 5 is 0.2

And if you input 2.5 when prompted for Number, the computer will store the value of 1 ÷ 2.5 in Reciprocal. This value is 0.4. While these values are mathematically correct, the display might not be what you want. You might want the user to see that the reciprocal of a number is simply 1 divided by that number. In other words, you might want your display to look like

The reciprocal of 5 is 1/5

or

The reciprocal of 2.5 is 1/2.5

Can you rewrite the pseudocode to display the reciprocal of a number as a fraction, rather than as a decimal number? One way would be to change the Write statement, which outputs the reciprocal to these two lines:

Write "The reciprocal of " + Number + " is " + 1 + "/" + Number

Write "The value of the reciprocal of " + Number + " is " + Reciprocal

For an input of 5, the display would then be

The reciprocal of 5 is 1/5

The value of the reciprocal of 5 is 0.2

For an input of 6.534, the display would be

The reciprocal of 6.534 is 1/6.534

The value of the reciprocal of 6.534 is 0.15305

Dealing with Square Roots

In some applications, it’s necessary to find the square root of a number. Most programming languages contain a built-in function that computes square roots. A function is a procedure that computes a specified value and can be called by a programmer at any time in a program. A typical square root function has the formSqrt(X) where X represents a number, a numeric variable, or an arithmetic expression.

The square root of a positive number is a number which, when multiplied by itself, gives back the original number. For example, the square root of 16 (16−−√) is 4since 4 * 4 = 16. However, another square root of 16 is −4. For every positive number, there are two possible square roots—a positive root and a negative root. Another example is the square root of 64, which is either +8 or −8 since +8 * +8 = 64 and −8 * −8 = 64. Given a positive number X, the square root function,Sqrt(X), gives the positive square root of X. So, Sqrt(4) = 2 and Sqrt(64) = 8. Moreover, since 0 * 0 = 0, we have Sqrt(0) = 0.

Here’s how this function works. When Sqrt(X) is encountered in a statement, the program finds the value of X and then calculates its positive square root. For example, the statements

Set Number1 = 7

Set Number2 = Sqrt(Number1 + 2)

Write Number2

will display the number 3. First the number 7 is stored in the variable Number1. In the next line, the expression inside the parentheses is evaluated as follows:

Number1 + 2 = 7 + 2 = 9

Then the Sqrt() function computes the square root of 9, which is 3. Next, that value is stored in the variable, Number2 and the value of Number2 is displayed.

In the above program segment, the square root function appears on the right side of an assignment statement. In general, the square root function may be used anywhere in a program that a numeric constant is valid, as shown in the following:

· Write Sqrt(16) is valid because 16 is a positive number and the Write statement says to output the result of taking the square root of 16.

· Input Sqrt(Number) is not valid because an Input statement must take in a value—it cannot take in a function.

Since the square root of a negative number (for example, Sqrt(−4)) is not a real number, taking such a square root is an  illegal operation and normally causes the program to crash.  Example  4.17  illustrates how to guard against a program crash when using the Sqrt() function.

Example 4.17 Avoid Illegal Operations with the Sqrt() Function

This program segment inputs a number, Number. If Number is not negative, it computes and displays its square root. If Number is negative, it displays a message indicating that the square root is not defined. Note that in this situation, it is perfectly fine to have Number = 0, because the square root of 0 is 0.

1 Write "Enter a number."

2 Write "This program will display its square root."

3 Input Number

4 If Number >= 0 Then

5 Write "The square root of " + Number + " is " + Sqrt ( Number) + "."

6 Else

7 Write "The square root of "+ Number +" is not defined."

8 End If

What Happened?

In the If-Then-Else structure, the Then clause displays the square root of the input Number if this operation is valid (if Number is greater than or equal to 0). For example, if the user inputs 25, the program segment outputs the following:

The square root of 25 is 5.

On the other hand, if Number is less than 0, the Else clause reports the fact that taking the square root in this case is an illegal operation. If, for example, the user inputs the number −16, the output would be as follows:

The square root of −16 is not defined.

Fill in the blank lines of the following code segment which is slightly different from  Example  4.17  but will give the same result:

Write "Enter a number."

Write "This program will display its square root."

Input Number

If Number < 0 Then

 Write

Fill in the code

Else

 Write

Fill in the code

End If

Program Defensively

Include error-trapping structures in your programs to catch and report the following kinds of errors:

1. Division by 0

2. A negative number input to the square root function

3. Input data that is out of the allowable range

Any one of these errors may cause your program to crash.

 Make Sure Your Programs Pass a Lot of Tests

When your program contains selection structures, it’s important to make enough test runs so that all blocks, or branches, of the structures are executed. For example, to test the code corresponding to  Example  4.17 , we must run the program at least twice. We must try at least once with a positive value for Number and at least once with a negative value for Number to make sure both the Then clause and the Else clause work correctly.

chapter 5.docx

Repetition Structures: Looping

In this chapter, we will begin to explore the topic of repetition structures (also called loops). We will discuss different types of loops and more advanced loop applications. The discussion of loops continues in  Chapter  6  .

After reading this chapter, you will be able to do the following:

· Distinguish between pre-test and post-test loops

· Identify infinite loops and loops that never get executed

· Create a flowchart using the loop structure

· Use relational and logical operators in loop conditions

· Construct counter-controlled loops

· Use counter-controlled loops to increment or decrement the counter by any integer value

· Construct For loops

· Create test conditions to avoid infinite loops and loops that never get executed

· Construct sentinel-controlled loops

· Use the following functions: Int(), Floor(), and Ceiling()

· Apply loops to data input and validation problems

· Apply loops to compute sums and averages

In the Everyday World Doing the Same Thing Over and Over and Knowing When to Stop

You may not remember, but you probably learned to walk about the time you were a year old. As you took your first step you had to figure out how to execute the following process:

· Put one foot in front of the other

At some point you did just that, and it was a major accomplishment. But this didn’t get you very far. If you wanted to walk across the room, you needed to extend this process to the following:

· Put the left foot in front of the right foot

· Put the right foot in front of the left foot

· Put the left foot in front of the right foot

· Put the right foot in front of the left foot and so forth

This is not a very efficient way to describe what you did. A detailed list of your actions as you ambled all over the house would be very long. Because you did the same thing over and over, the following is a much better way to describe your actions:

· Repeat

· Put the left foot in front of the right foot

· Put the right foot in front of the left foot

· Until you get across the room

This way is short, convenient, and just as descriptive. Even if you want to take hundreds or thousands of steps, the process can still be described in four lines. This is the basic idea of a loop.

Walking is just one of many examples of loops in your daily life. For example, if you have a large family and need to prepare lunches in the morning for everyone, you can do the following:

· Repeat

· Make a sandwich

· Wrap the sandwich

· Place the sandwich in a lunch bag

· Place an apple in the lunch bag

· Place a bag of chips in the lunch bag

· Continue until lunches have been made for everyone in the family

Where else do you encounter a looping process? How about reading your email (one message at a time) or brushing your teeth? If you have a programming class on Tuesdays at 11:00 a.m., you go to class every Tuesday at 11:00 a.m. until the end of the semester. You do the “go to programming class” loop until the end of the semester. After you read this chapter (one word at a time), you’ll be ready to place loops in your programs as well.

5.1 An Introduction to Repetition Structures: Computers Never Get Bored!

You have already learned that all computer programs are created from three basic constructs: sequence, decision, and repetition. This chapter discusses repetition, which in many ways is the most important construct of all. We are lucky that computers don’t find repetitious tasks boring.

Regardless of what task we ask a computer to perform, the computer is virtually useless if it can perform that task only once. The ability to repeat the same actions over and over is the most basic requirement in programming. When you use any software application, you expect it to open the application and do certain tasks. Imagine if your word processor was programmed to make your text bold only once or if your operating system allowed you to use the copy command only once. Each computer task you perform has been coded into the software by a programmer, and each task must have the ability to be used over and over. In this chapter, we will examine how to program a computer to repeat one or more actions many times.

Loop Basics

All programming languages provide statements to create a  loop. The loop is the basic component of a  repetition structure  . These statements are a block of code, which under certain conditions, will be executed repeatedly. In this section, we will introduce some basic ideas about these structures. We will start with a simple illustration of a loop shown in  Example  5.1 . This example uses a type of loop called a  Repeat...Until loop. Other types of loops are discussed throughout this chapter.

Example 5.1 Simply Writing Numbers

This program segment repeatedly inputs a number from the user and displays that number until the user enters 0. The program then displays the words List Ended.

1 Declare Number As Integer

2 Repeat

3 Write "Please enter a number: "

4 Input Number

5 Write Number

6 Until Number == 0

7 Write "List Ended"

In the pseudocode, the loop begins on line 2 with the word Repeat and ends on line 6 with Until Number == 0. The  loop body is contained in lines 3, 4, and 5. These are the statements that will be executed repeatedly. The body of a loop is executed until the  test condition following the word Until on line 6 becomestrue. In this case, the test condition becomes true when the user types a 0. At that point, the loop is exited and the statement on line 7 is executed.

What Happened?

Let’s trace the execution of this program, assuming that the user enters the numbers 1, 3, and 0, in that order:

· When the execution begins, the loop is entered, the number 1 is input, and this number is displayed. These actions make up the first pass through the loop. The test condition, “Number == 0?” is now “tested” on line 6 and found to be false because at this point, Number == 1. Therefore, the loop is entered again. The program execution returns to line 2, and the body of the loop is executed again. (Recall that the double equals sign, ==, is a comparison operator and asks the question, “Is the value of the variable Number the same as 0?”)

· On the second pass through the loop, the number 3 is input (line 4) and displayed (line 5), and once again the condition (line 6), Number == 0 is false. So the program returns to line 2.

· On the third pass through the loop, the number 0 is input and displayed. This time the condition Number == 0 is true, so the loop is exited and execution transfers to line 7, the statement after the loop.

· The words List Ended are displayed and the program is complete.

The flowchart for  Example  5.1  is shown in  Figure  5.1 .

Iterations

We have said that the loop is the basic component of a repetition structure. One of the main reasons a computer can perform many tasks efficiently is because it can quickly repeat tasks over and over. The number of times a task is repeated is always a significant part of any repetition structure, but a programmer must be aware of how many times a loop will be repeated to ensure that the loop performs the task correctly. In computer lingo, a single pass through a loop is called a loop iteration. A loop that executes three times goes through three iterations.  Example  5.2  presents the iteration process.

Example 5.2 How Many Iterations?

This program segment repeatedly asks the user to input a name until the user enters “Done.”

1 Declare Name As String

2 Repeat

3 Write "Enter the name of your brother or sister: "

4 Input Name

5 Write Name

6 Until Name == "Done"

What Happened?

This pseudocode is almost the same as shown in  Example  5.1  except that the input in this example is string data instead of integer data. The loop begins on line 2 with the word Repeat and ends on line 6 with Until Name == "Done". The loop body is contained in lines 3, 4, and 5. How are the iterations counted? Each time these statements are executed, the loop is said to have gone through one iteration.

Figure 5.1 A simple repetition structure flowchart

· Let’s assume that this program segment is used to enter a list of a user’s brothers and sisters. If Hector has two brothers named Joe and Jim and one sister named Ellen, the loop would complete four iterations. Joe would be entered on the first iteration; Jim on the second iteration; Ellen on the third iteration, and the word Done would be entered on the fourth iteration.

· If Marie, on the other hand, has only one sister named Anne, the program would go through two iterations—one to enter the name Anne and the second to enter the word Done.

· And if Bobby were an only child, the program would only complete one iteration since Bobby would enter Done on the first iteration.

Later in this chapter, we will see how to create a loop that does not require the test condition count as one of the iterations.

Beware the Infinite Loop!

In  Example  5.1 , we saw that the user was prompted to enter any number and that number would be displayed on the screen. If the user started with the number 234,789 and worked his way down, entering 234,788, then 234,787, and so forth, the computer would display 234,790 numbers (including the 0 that terminates the loop).

However, after the user entered the last number, 0, the loop would end. It would be a lot of numbers, but it would end. On the other hand, what would happen if the loop was written as shown in  Example  5.3 ?

Example 5.3 The Dangerous Infinite Loop

In this example, we change the test condition of  Example  5.1  to a condition that is impossible to achieve. The user is asked to enter a number on line 3, and line 4 takes in the user’s input, which is stored in the variable Number. Line 5 sets a new variable, ComputerNumber equal to that number plus one. The loop will continue to ask for and display numbers until the value of Number is greater than ComputerNumber. That condition will never be met because on each pass through the loop, regardless of what number the user enters, ComputerNumber will always be one greater. Thus, the loop will repeat and repeat, continually asking for and displaying numbers.

1 Declare Number, ComputerNumber As Integer

2 Repeat

3 Write "Please enter a number: "

4 Input Number

5 Set ComputerNumber = Number + 1

6 Write Number

7 Until Number > ComputerNumber

8 Write "The End"

When will it end? Never. The words "The End" will never be displayed.

If, as shown in  Example  5.3 , a loop’s test condition is never satisfied, then the loop will never be exited, and it will become an  infinite loop. Infinite loops can wreak havoc on a program, so when you set up a loop and put in a test condition, be sure that the test condition can be met. Computers don’t mind doing a task many times but forever is simply too many!

Don’t Let the User Get Trapped in a Loop

There is one more important point to mention about  Examples  5.1  and  5.2 . In both of these examples, we have test conditions that can easily be met. As soon as a user enters 0 for the number in  Example  5.1 , the loop ends. As soon as the user enters the word Done in  Example  5.2 , the loop ends. But how would the user know that 0 or Done is the cue for the program segment to end? It is important for the programmer to make it clear, by means of a suitable prompt, how the user will terminate the action of the loop. In  Example  5.1 , the following would be a suitable prompt:

Write "Enter a number; enter 0 to quit."

In  Example  5.2 , the following would be a suitable prompt:

Write "Enter the name of your brother or sister:"

Write "Enter the word 'Done' to quit."

In the type of loops we used in these two examples, the loop continues until the user ends it. Other loops end without a user input. Regardless of what type of loop you write, you always wish to avoid the possibility that the loop will continue without an end. Therefore, you must ensure that the test condition can be met and, if the user must enter something special to end the loop, be sure it’s clear.

Relational and Logical Operators

The condition that determines whether a loop is re-entered or exited is usually constructed with the help of relational and logical operators. We will briefly review these operators.

The following are the six standard  relational operators and the programming symbols that we will use in this book to represent them:

· equal to (or “is the same as”): ==

· not equal to: !=

· less than: <

· less than or equal to: <=

· greater than: >

· greater than or equal to: >=

All six operators can be applied to either numeric or character string data. Recall that the double equals sign, the comparison operator (==) is different from the assignment operator (=). While the assignment operator assigns the value on the right side of the equals sign to the variable on the left side, the comparison operator compares the values of the variable or expression on the left side of the operator with the value of the variable, expression, number, or text on the right side. It returns only a value of false (if the two values are different) or true (if the two values are the same). When a comparison operator is used, neither the value on the left side nor the statement on right side changes from its initial value. The result of any relational operator is always a value of true or false.

The basic logical operators, OR, AND, and NOT, are used to create more complicated conditions ( compound conditions) from given simple conditions. If S1 andS2 are conditions (such as Number <= 0 or Response == "Y") then we have the following:

· S1 OR S2 is true if  either S1 is true or S2 is true or both are true; it is false if both S1 and S2 are false.

· S1 AND S2 are true if  both S1 and S2 are true; it is false if either S1 or S2 or both are false.

·  NOT S1 is true if S1 is false; the condition is false if S1 is true.

If Number = 3 and Name = "Joe", then we have the following compound conditions:

· (Number == 1) OR (Name == "Joe") is true but (Number == 1) AND (Name = "Joe") is false because one of the simple conditions (Number == 1) is false.

· NOT ((Number == 1) OR (Name == "Joe")) is false because (Number == 1) OR (Name == "Joe") is true.

Constructing Flowcharts with a Loop Structure

The use of flowcharts in program design is a topic often debated. Some programmers cannot imagine designing a program without flowcharts, while other programmers rarely use them. Most programmers, however, follow the same approach that is used in this textbook ; we combine pseudocode and flowcharts in our designs. There are certain programs that lend themselves more easily to design with pseudocode and others that work better with flowcharts. Repetition structures are often more easily visualized with flowcharts than with pseudocode because the loop can be seen pictorially.

Self Check for Section 5.1

1. 5.1 What numbers will be displayed if code corresponding to the following pseudocode is run?

a. Declare Number As Integer

b. Set Number = 1

c. Repeat

d. Write 2 * Number

e. Set Number = Number + 1

f. Until Number == 3

g. Declare Number As Integer

h. Set Number = 1

i. Repeat

j. Write 2 * Number

k. Set Number = Number + 1

l. Until Number > 3

2. 5.2 What will be displayed if code corresponding to the following pseudocode is run? Assume the user is 17 years old.

3. Declare Age As Integer

4. Declare NewAge As Integer

5. Declare Number As Integer

6. Set Number = 2

7. Write "Enter your age: "

8. Input Age

9. Repeat

10. Set NewAge = Age + Number

11. Write "In " + Number + " years you will be " + NewAge

12. Set Number = Number + 1

Until Number == 4

13. 5.3 Indicate whether each of the following conditions is true or false.

a. 5 == 5

b. 5 != 5

c. 5 < 5

d. 5 <= 5

e. 5 > 5

f. 5 >= 5

14. 5.4 If C1 = "Jo" and C2 = "jo", indicate whether each of the following is true or false.

a. C1 >= "Ann"

b. (C1 == "Jo") AND (C2 == "Mo")

c. C1 == "Jo "

d. (C1 == "Jo") OR (C2 == "Mo")

e. C1 <= "Joe"

f. NOT(C1 == C2)

5.2 Types of Loops

As you learn to write more complicated programs, you will find that loops are one of your most indispensable tools. You’ll use loops to load data, manipulate data, interact with the user, and much more. In fact, it would be difficult to imagine any program that does significant processing that does not contain loops. Just as one size does not fit all when it comes to choosing a screwdriver and nails for a carpentry project, loops come in various types as well. One type of loop may work well for one specific program’s need, while another type fits a different program’s design. In this section, you will learn about several types of loops and how and why one may be chosen over another in a specific situation.

Pre-Test and Post-Test Loops

Basically, all repetition structures can be divided into two fundamental types:  pre-test loops and  post-test loops. The following loop (from  Example  5.1 ) is an example of a post-test loop because the test condition occurs  after the body of the loop is executed:

Declare Number As Integer

Repeat

Write "Enter a number: "

Input Number

Write Number

Until Number == 0

Write "List Ended"

 The Do . . . While Loop

In the previous section, we used the pseudocode Repeat . . . Until for a post-test loop. Many languages include a slightly different syntax for post-test loops. These loops begin with a Do statement and close with a While statement. The following example shows this syntax in pseudocode and does the same thing as the Repeat . . . Until example:

Declare Number As Integer

Do

Write "Enter a number: "

Input Number

Write Number

While Number != 0

Write "List Ended"

Notice, though, that the test condition is altered to fit the requirements of the Do . . . While loop. In a Repeat . . . Until loop, the loop is executed until a specified condition  becomes true. In a  Do . . . While loop, the loop is executed  while a specified condition  remains true.

 Creating Loop Examples With RAPTOR

While most of the examples in this chapter can be implemented with RAPTOR, it is recommended that you read the first part of  Section 5.6  before attempting to implement loops in RAPTOR. You may have to alter the way test conditions are written in the textbook examples for your programs to work in RAPTOR.

In a pre-test loop, the test condition occurs  before the body of the loop is executed. The  While loop is one type of a pre-test loop. This significant difference warrants some careful examination and is illustrated in  Examples  5.4  through  5.6 .

Example 5.4 Writing Numbers with a Pre-Test Loop

The following program segment does almost the same thing as shown in  Example  5.1 . However, in  Example  5.1 , we tested to see if the Number == 0after a number had been displayed. In the following, we test to see if Number == 0 on line 4, before the first number has been displayed:

1 Declare Number As Integer

2 Write "Enter a number; enter 0 to quit."

3 Input Number

4 While Number != 0

5 Write Number

6 Input Number

7 End While

8 Write "List Ended"

What Happened?

In this pseudocode, the statement on line 4 begins with the word While and is followed by the test condition Number != 0, which as you remember, means “isNumber not equal to 0?” The last statement in the loop is End While on line 7. All the statements between the While and the End While (lines 5 and 6) comprise the body of the While loop. When the loop is entered, the test condition is evaluated. If it is found to be true, the body of the loop is executed and control then returns to line 4, the top of the loop. If the test condition is found to be false, then the loop is exited and the statement following End While on line 8 is executed next.

Let’s walk through the execution of this program segment using the same values that we tried in  Example  5.1  to see what happens now. We’ll take the first value the user enters for Number to be 1, and then on the next two passes through the loop the user will enter the numbers 3 and 0. In this case, execution flows as follows:

· When execution begins, the number 1 is input (line 3).

· On line 4, the While statement is executed. It checks the test condition Number != 0, which is found to be true since Number = 1 at this point. Thus, the body of the loop is executed.

· Lines 5 and 6 are the body of the loop. Line 5 causes a 1 to be displayed, and line 6 asks for another number. The user inputs a 3. Then control returns to the top of the loop, on line 4. Lines 1, 2, and 3 are never executed again in this program segment.

· Line 4 tests the condition again and because Number now equals 3, the test is true and a second pass is made through the loop.

· This time 3 is displayed (line 5) and 0 is input (line 6) and control returns to the top of the loop.

· Once again, the test condition is evaluated on line 4. Because Number is now equal to 0, the test condition is found to be false. Therefore, the loop is exited  before the 0 is displayed and control jumps to line 8.

· Line 8 causes the words List Ended to be displayed and the program is complete.

In  Example  5.1 , if the numbers 1, 3, and 0 are input, then the numbers 1, 3, and 0 are all displayed (and then the words List Ended). In  Example  5.4 , with the same input, only the numbers 1 and 3 are displayed (and then the words List Ended). What makes the display for this example different from  Example  5.1 ? That’s the key to understanding pre-test and post-test loops. In  Example  5.1 , because the condition was tested after the loop body statements were executed, the last number input (0) was also displayed. In  Example  5.4 , because the condition was tested before the loop body statements were executed, the last number input (0) caused the condition to fail before a 0 could be displayed.

What would happen, if in  Example  5.4 , the user inputs a 0 on line 3? In this case, the test on line 4 would ask “Is Number not equal to 0?” and the answer would be "no" because Number  is equal to 0. Therefore, the test condition would be false, the loop body statements would never be executed, and control would immediately jump to line 8.

What would happen if, in  Example  5.4 , we left out line 3? In  Example  5.1 , the post-test loop, the first value of Number, was input by the user within the loop body and then the condition was tested. In  Example  5.4 , we asked the user to input a value for Number before the test condition. If we left off this line, the first line of this loop would be a test of the value of a variable named Number. Unless that variable had been given a value somewhere else in the program, the programmer would have no control at all over what would happen in the first pass of this loop. If the variableNumber had a value of 0 from a previous assignment, the loop would never execute. If it had a value of 23 from a previous assignment, the loop would work fine, although a 23 would be displayed, even if the user did not want to see 23. And, if the memory location assigned to Number had never been assigned any value, the program might crash completely or execute in an undetermined manner, depending on the computer’s operating system, the language used, and so on. So the initial value of a variable used is a very important consideration!

Example 5.5 Using the Pre-Test Loop Wisely

In  Example  5.2  we saw that, no matter how many names a user entered, the last name on the displayed list would be Done. This is surely not desirable. We can eliminate this unwanted display by changing the pseudocode of  Example  5.2  to a pre-test loop, shown as follows:

1 Declare Name As String

2 Write "Enter the name of your brother or sister:"

3 Write "Enter the word Done to quit."

4 Input Name

5 While Name != "Done"

6 Write Name

7 Input Name

8 End While

What Happened?

Now, if Hector from  Example  5.2  enters Joe, Jim, Ellen, and Done the display would be:

Joe

Jim

Ellen

The word Done would not be displayed because after the third iteration of the loop, the value of Name would be Done, the test condition on line 5 would confirm that the condition no longer is true, and the loop body would not be executed a fourth time.

With this pseudocode, our only-child, Bobby, would not see the word Done on his list of no brothers and sisters. He would simply enter the word Done at the first prompt, the condition would be tested on line 5, found to be false, and control would jump to whatever instructions came after line 8. The loop would never be entered.

There are several basic differences between pre-test and post-test loops. They are:

· By definition, a pre-test loop has its test condition (the statement that determines whether the body of the loop is executed) at the top. A post-test loop has its test condition at the bottom.

· The body of a post-test loop is always executed at least once, but the body of a pre-test loop won’t be executed at all if its test condition is initially false.

· Before a pre-test loop is entered, the variables that appear in its test condition must be initialized; that is, they must be assigned some value. This isn’t necessary in the post-test loop because the test condition variables may be initialized within the body of the loop.

Figure  5.2  illustrates the logical differences between pre- and post-test loops through flowcharts.  Example  5.6  demonstrates how to use a pre-test loop to display squares of numbers.

Figure 5.2 Pre- and post-test loop flowcharts

Example 5.6 Numbers Squared

The following program segment uses a pre-test loop to display the squares of numbers input by the user until he or she enters zero or a negative number. The zero or negative number is not displayed.

Declare Number As Integer

Write "Enter a number:"

Input Number

While Number > 0

Write Numberˆ2

Input Number

End While

Notice that we initialize the variable Number by using an Input statement just prior to entering the loop. Trace this pseudocode with the test data 4,3, 2, 1, and −1 to see for yourself how it works. Check that the numbers you would expect to see written to the screen are 16, 9, 4, and 1.

Either a pre-test loop or a post-test loop can be used to accomplish a given task; although as you will discover, some tasks are easier to accomplish with pre-test loops and others with post-test loops.

Indent the Body of a Loop

To make it easier to read your pseudocode and the corresponding program code, you should indent the body of a loop relative to its first and last statements. For example, compare the loop on the right, which is indented, with that on the left, which is not, as follows:

Not indented

Indented

Repeat

Input Number

Write Number

Until Number == 0

Repeat

  Input Number

  Write Number

Until Number == 0

As you begin to write longer and more complicated programs, this style becomes more and more important. It will enable you to quickly identify where loops begin and end as you debug a program.

Counter-Controlled Loops

All the loops that we have seen so far end when the user types in a certain value. There are, of course, many times when you want a loop to execute a certain number of times without any user input. One way to construct such a loop is with a special type of pre-test loop known as a  counter-controlled loop—a loop that is executed a fixed number of times, where that number is known prior to entering the loop for the first time.

A counter-controlled loop contains a variable (the  counter) that keeps track of the number of passes through the loop (the number of loop iterations). When the counter reaches a preset number, the loop is exited. In order for the computer to execute the loop a certain number of times, it must keep track of how many times it goes through the loop. It stores this number in the counter.

Using a Counter

To keep track of how many times a loop has been executed using a counter, you must define, initialize, and either  increment (to count up) or  decrement (to count down) the counter. Self-Check Exercises 5.1 and 5.2 use a counter without actually defining it as such. The code to keep a count like this may seem a bit strange at first, but it will quickly make sense. Although there are small syntax differences in different programming languages, the code for a counter in any language is always similar. It is illustrated in  Example  5.7  and described in the following list:

1. Define a counter: the counter is a variable. It is always an integer because it counts the number of times the loop body is executed and you cannot tell a computer to do something 5 3/4 times. Common variable names for counters are counter, Count, I, or j. For now, we will call our counter Count.

2. Initialize the counter: set the counter at a beginning value. Although a counter can begin at any integer value—often determined by other factors in the program—for now, we will usually set our counter equal to 0 or 1 (Set Count = 0 or Set Count = 1, depending on the program’s requirements).

3. Increment the counter: the computer counts the way you did when you were young. To count by ones, the computer takes what it had before and adds one. So the code for a computer to count by ones looks like Count + 1. Then, to store the new value where the old value was, you use the statement Set Count= Count + 1. This takes the old value, adds one to it, and stores the new value where the old value was.

Example 5.7 Using a Counter to Display the Squares of Numbers

A common use of counter-controlled loops is to print tables of data. For example, suppose we want to display the squares of a certain number of positive integers, where that number is to be entered by the user and stored in a variable named PositiveInteger. The pseudocode for this process is shown as follows:

1 Declare PositiveInteger As Integer

2 Declare Count As Integer

3 Write "Please enter a positive integer: "

4 Input PositiveInteger

5 Set Count = 1

6 While Count <= PositiveInteger

7 Write Count + " " + Countˆ2

8 Set Count = Count + 1

9 End While

What Happened?

Let’s walk through this pseudocode, one line at a time.

· Lines 1 and 2 declare the two integer variables.

· Line 3 asks the user to input a positive integer.

· Line 4 stores the value entered by the user in a variable named PositiveInteger.

· Line 5 sets Count equal to its first value—we initialize it to 1—before entering the loop.

· Line 6 is the beginning of the loop. It tests to see if Count is less than or equal to PositiveInteger. We want the loop body statements to execute so that the number and its square are displayed, for all numbers from 1 up to and including the value of PositiveInteger. In other words, if you entered 3 forPositiveInteger, you would want to see the following:

· 1 1

· 2 4

3 9

· Line 7 writes the value of Count and the square of Count to the screen, separated by a space.

· Line 8 increments Count by 1 within the loop. Then the program goes back to the beginning of the loop on line 6.

· Line 9 is only reached when the value of Count becomes greater than the value of PositiveInteger.

A flowchart corresponding to this pseudocode is shown in  Figure  5.3 .

What would happen if, in  Example  5.7 , the user inputs a value of 1 for PositiveInteger? Line 6 would test to see if PositiveInteger was less than or equal to Count. This would be true and the loop body would execute once. Then Count would be incremented to 2, which is greater thanPositiveNumber so the loop would be exited. The display would be as follows:

  1 1

What would happen if, in this example, the user inputs a value of 0 for PositiveInteger? The test condition would immediately be false, the loop body would never execute, and there would be nothing displayed.

Try this: Go through  Example  5.7  by hand, using 6 as the value entered for PositiveInteger. Check to make sure your results are as follows:

  1 1

  2 4

  3 9

  4 16

  5 25

  6 36

Counting Up, Down, and Every Way

Counters don’t just have to count by ones and counters don’t just have to count up. You can start a counter with any number you want and count up to a certain number, as we did in  Example  5.7 , or you can count down to a certain number, as illustrated in  Example  5.8 . We can start a counter at any number and count up (or down) by twos, fives, or by any whole number.

Figure 5.3 A flowchart that uses a counter in a loop

Example 5.8 Countdown to Blastoff Using a Decremental Counter

Let’s display a countdown for a rocket to blast off to the moon. The countdown begins at 100 and counts down to 1 at one-second intervals as follows:

1 Declare Count As Integer

2 Set Count = 100

3 Write "Countdown in . . . ";

4 While Count > 0

5 Write Count + " seconds"

6 Set Count = Count − 1

7 End While

8 Write "Blastoff!"

Notice that in this example, as in our previous example, the counter has two purposes. Not only does it count how many times the loop has been repeated but also it is used in the output. This may not always be true. Sometimes a counter simply counts the number of iterations in a loop and sometimes, as here, it serves a dual purpose.

Example  5.9  illustrates a loop with a counter that is used only to count the number of iterations but is not used in the output.

Example 5.9 A Few of Your Favorite Things

Let’s assume you are writing a program to allow users to create a profile on a website. In this program segment, a counter is used to allow the user to enter his or her three favorite leisure time activities. The three activities will be displayed, but the counter is used only to keep track of the number of iterations.

1 Declare Count As Integer

2 Declare Activity As String

3 Set Count = 1

4 Set Activity = " "

5 Write "Enter 3 things you like to do in your free time:"

6 While Count < 4

7 Input Activity

8 Write "You enjoy " + Activity

9 Set Count = Count + 1

10 End While

If the user enters biking, football, and computer programming for the three activities, the display would look like this:

You enjoy biking

You enjoy football

You enjoy computer programming

The flowchart for this program segment is shown in  Figure  5.4  .

It is possible to use the counter to keep track of the number of iterations, to use it as part of the display, and to combine this with displaying other variables. Here, we will spruce up the output of  Example  5.9  and use the counter to help us do that.

1 Declare Count As Integer

2 Declare Activity As String

3 Set Count = 1

4 Set Activity = " "

5 Write "Enter 3 things you like to do in your free time:"

6 While Count < 4

7 Input Activity

8 Write Count + ". You enjoy " + Activity

9 Set Count = Count + 1

10 End While

Now, if the user enters biking, football, and computer programming for the three activities, the display would look like this:

1. You enjoy biking

2. You enjoy football

3. You enjoy computer programming

Figure 5.4 A flowchart that uses the counter to keep track of the number of iterations

Self Check for Section 5.2

1. 5.5 Create flowcharts for the program segments of  Examples  5.5  and  5.6 .

2. 5.6 The following program is supposed to input numbers from the user and display them as long as 0 is not entered, but a statement is missing. What is the missing statement? Insert it in its proper place.

3. Declare Number As Integer

4. Input Number

5. While Number != 0

6. Write Number

End While

7. 5.7 The variable that stores the number of times a loop has completed is called a              .

8. 5.8 True or false? It is possible to increment a counter by 14 on each loop iteration.

9. 5.9 True or false? It is possible to decrement a counter by any multiple of 4.

10. 5.10 True or false? The counter can be any real number.

11. 5.11 What numbers will be displayed when a code corresponding to the following pseudocode is run?

a. Declare N, K As Integer

b. Set N = 6

c. Set K = 3

d. While K <= N

e. Write N + " " + K

f. Set N = N − 1

g. End While

h. Declare K As Integer

i. Set K = 10

j. While K >= 7

k. Write K

l. Set K = K − 2

m. End While

12. 5.12 Create a pseudocode that does the same thing as the following program segment but uses a post-test loop instead of a pre-test loop. You can use either a Repeat . . . Until or a Do . . . While structure.

13. Declare W As Integer

14. Declare Count As Integer

15. Set Count = 1

16. Set W = 2

17. While Count < 4

18. Write Count * W

19. Set Count = Count + 1

End While

5.3 The For Loop

Most programming languages contain a statement that makes it easy to construct a counter-controlled loop. To create a built-in counter-controlled loop, we introduce the For loop. The  For loop provides a shortened method to initialize the counter, to tell the computer how much to increase or decrease the counter for each pass through the loop, and to tell the computer when to stop.

The For Statement

We will use the following pseudocode to represent the statement that creates a built-in counter-controlled loop that increases the value of the counter by 1 on each iteration:

For (Counter = InitialValue; Test Condition; Counter++)

body of the loop

End For

This kind of statement will repeatedly execute the body of the loop starting with Counter equal to the specified InitialValue and incrementing Counter by 1 on each pass through the loop. Counter++ acts just like the statement Set Counter = Counter + 1. This continues until the Test Condition is met. While we will discuss each part of the For loop in detail in this section,  Example  5.10  demonstrates how the simplest For loop works.

Example 5.10 The Action of a For Loop

For (Count = 1; Count <= 4; Count++)

Write Count

End For

In this example, the loop is executed with Count equal to 1 on the first pass, then 2, then 3, and finally 4. The output of this program segment consists of the numbers 1, 2, 3, and 4.

There are three statements within the parentheses after the word For, separated by semicolons. The first statement sets the counter to an initial value. The second statement describes the test condition. The last statement tells the computer how much to increase or decrease the counter on each subsequent pass through the loop. In  Example  5.10 , the counter was incremented by 1 on each pass. However, a general form of a For loop is as follows:

For(Counter = InitialValue; Test Condition; Increment/Decrement)

body of the loop

End For

Let’s discuss each of the three statements in a bit more detail. In a typical For statement, Counter must be a variable, Increment or Decrement is normally a number, and InitialValue and Test Condition may be constants, variables, or expressions.

The Initial Value

The first statement sets the counter to its initial value. The initial value can be any integer constant, such as 1, 0, 23, or −4. The initial value can also be another numeric variable. For example, if a variable named LowNumber was set equal to an integer prior to entering the For loop, the counter could be initialized to the value of LowNumber. The first statement in the For loop would then look like this: Count = LowNumber. Similarly, the counter could be set equal to an expression containing a numeric variable and a number, such as Count = (LowNumber + 3). However, the counter itself must be a variable and the initial value must be an integer.

· Count = 5 is a valid initialization of a counter.

· Count = NewNumber is a valid initialization of a counter, if NewNumber is an integer variable.

· Count = (NewNumber * 2) is a valid initialization of a counter if NewNumber is an integer variable.

· Count = (5/2) is not a valid initialization of a counter because 5/2 is not an integer.

· 23 = Count is not a valid initialization of a counter.

The Test Condition

The test condition is, perhaps, the most important statement of the three. It is important to understand what the test condition represents, where the test is made, and what happens after the condition is tested. The test condition asks the question, “Is the counter within the range specified by this condition?” If the test condition is, for example, Count < 10, then the question asked is, “Is the value of Count less than 10?” If the answer to that question is "yes" then the loop executes again. If the answer is "no" then the loop is exited. This means that when Count is equal to 10, the loop will be exited. However, if the test condition were Count <= 10, the question asked is, “Is the value of Count less than or equal to 10?” In this case, the loop will not be exited until Count is at least 11.

Another important consideration about test conditions in any loop, including Repeat...Until, Do...While, and While loops as well as For loops, is when the check of the test condition occurs. As we have seen, the test condition is checked at the end of a loop in a post-test loop and at the beginning in a pre-test loop. This is clear from the language of those loops, but it is not so clear with a For loop. In a For loop, the test condition is checked at the beginning. If the initial value of the counter passes the test condition, the loop is entered once. After the loop body executes once, the counter is then either incremented or decremented, and the test condition is checked again.

The test condition can also be a number, another variable with a numeric value, or an expression containing variables and numbers. For example, if NewNumber is an integer variable:

· Count < 5 is a valid test condition and a loop with this condition will execute until Count has the value of 5 or more.

· Count >= 6 is a valid test condition and a loop with this condition will execute until Count becomes 5 or less.

· Count >= NewNumber is a valid test condition and will execute until Count becomes less than the value of NewNumber.

· Count < (NewNumber + 5) is a valid test condition. A loop with this condition will execute until Count becomes greater than or equal to the value of NewNumber + 5.

The Increment/Decrement Statement

The increment or decrement statement does the same thing that the Set Count = Count + 1 or Set Count = Count − 1 statements used in  Examples  5.7 5.9  did. However, many programming languages use a shorthand method to increment or decrement the counter. In our pseudocode, we will use a similar shorthand as follows:

· Count++ increments the variable named Count by 1 (i.e., it counts up).

· Count−− decrements the variable named Count by 1 (i.e., it counts down).

· To increase or decrease a counter by any integer other than 1, we will use the following shorthand:

· Count+2 increments Count by 2. For example, if Count = 0 initially, it will equal 2 on the next pass through the loop, 4 on the next pass, and so on. This shorthand is comparable to the following pseudocode: Count = Count + 2.

· Count−3 decrements Count by 3. For example, if Count = 12 initially, it will equal 9 on the next pass through the loop, then 6, then 3 and so on. This shorthand is comparable to the following pseudocode: Count = Count − 3.

· Therefore, Count+X will increase Count by the value of X and Count−X will decrease Count by the value of X after each pass through the loop.

Examples  5.11  and  5.12  demonstrate incremental and decremental For loops.

Example 5.11 An Incremental For Loop

A For loop that increments a counter by 5 and displays how to count by fives from 0 to 15 would, thus be written as follows:

For (Count = 0; Count <= 15; Count+5)

Write Count

End For

In this program segment, the counter is the variable named Count and it is initialized to the constant 0. The increment is 5; Count+5 tells the computer to add5 to the value of Count for each pass through the loop. The test condition is the expression Count <= 15.

What Happened?

On the first pass through this loop, Count = 0, a 0 is written to the screen, and 5 is added to Count. Then the test condition is checked. The check determines that Count is not greater than 15, so another pass is made through the loop. On the second pass, Count = 5, a 5 is written to the screen, and 5 is added toCount. The test condition is checked again. Since 10 (the new value of Count) is not greater than 15, the loop is executed again. On the third pass, Count = 10 so a 10 is written to the screen, and 5 is added to Count. The test condition then determines that Count is still not greater than the limit (15 is equal to 15but not greater than 15) and the loop is executed one more time.

On this last pass through the loop, Count = 15 so a 15 is written to the screen, Count is again incremented by 5 so its value is now 20. This time, when the test condition is checked, Count fails the test and the loop ends. The output of this program segment would be as follows:

0

5

10

15

The pseudocode that corresponds to the For loop of  Example  5.11  is as follows:

Set Count = 0

While Count <= 15

Write Count

Set Count = Count + 5

End While

Notice that the variable Count is initialized before entering the While loop and the increment/decrement statement occurs inside the loop body in this pseudocode that corresponds to a For loop. To implement a For loop in RAPTOR, a flowchart similar to this comparable pseudocode must be used.

Example 5.12 A Decremental For Loop

A For loop that decrements a counter by 5 and displays how to count down by fives from 15 to 0 would thus be written as follows:

For (Count = 15; Count >= 0; Count−5)

Write Count

End For

In this program segment, Count is initialized to the constant 15. The decrement is 5; Count−5 tells the computer to subtract 5 from the value of Count for each pass through the loop. The test condition is the expression Count >= 0 and it means that, when Count becomes less than 0, the loop will end. The output of this program segment would be as follows:

15

10

5

0

The For Loop in Action

To summarize our discussion to this point, a For loop works as follows: when the loop is entered, the Counter is set equal to an InitialValue. If theInitialValue immediately passes the test of the Test Condition, then the body of the loop is executed. If the Counter doesn’t pass the test, the loop is skipped and the statement following End For is executed next.

On each pass through the loop, the Counter is increased or decreased by the value of Increment/Decrement. Then, if the new value of the Counter passes theTest Condition, the body of the loop is executed again. When the value of the Counter no longer is within the range of the Test Condition, the loop is exited and the statement following End For is executed next.  Example  5.13  demonstrates the use of an expression as a test condition.

Example 5.13 Using an Expression for a Test Condition

In the following For loop, the test condition is not a constant but an expression. In this loop, the counter is increased by 3 with each iteration until it reaches the value of two more than the variable named myNumber:

Set MyNumber = 7

For (Count = 1; Count <= (MyNumber + 1); Count+3)

Write Count

End For

The display after this segment is executed will look like this:

1

4

7

What Happened?

On the first pass, Count = 1. The test condition states that the loop should be executed again so long as Count is less than or equal to MyNumber + 1, which is 8. On the second pass, Count = 1 + 3 = 4. On the third pass, Count = 4 + 3 = 7. On the fourth pass, Count = 7 + 3 = 10. At this point, Count fails the Test Condition so the loop ends.

Example  5.14  allows the user to control the test condition.

Example 5.14 Using a For Loop to Display the Squares of Numbers

The following For loop has the same effect as the While loop that we constructed in  Example  5.7 . It displays a table of numbers and their squares from 1 toPositiveInteger. The test condition in this example depends on the user’s input of a value for PositiveInteger.

1 Declare Count As Integer

2 Declare PositiveInteger As Integer

3 Write "Please enter a positive integer: "

4 Input PositiveInteger

5 For (Count = 1; Count <= PositiveInteger; Count++)

6 Write Count + " " + Countˆ2

7 End For

The flowchart showing the action of the incremental For loop of  Example  5.14  is shown in  Figure  5.4  . This flowchart also illustrates the While loop of  Example  5.7 . The logic is the same; the differences are particular to the programming language used and the preferences of the programmer.

Examples  5.15 5.17  provide a few more examples and illustrate additional features of For loops.

Example 5.15 Using a For Loop to Count by Twos

This program provides an example of a For loop with an increment value that is not equal to 1. It displays the odd numbers between 1 and 20.

1 Declare Count As Integer

2 For (Count = 1; Count <= 20; Count+2)

3 Write Count

4 End For

The numbers that would be displayed on the screen would be all the odd numbers from 1, going up to and including 19.

What Happened?

On the first pass through this loop, Count is initialized to 1 (line 2), displayed (line 3), and incremented by 2 (due to the Count+2 statement on line 2). Now Count = 3, so on the second pass, the test condition (Count <= 20 on line 2) is also checked. Since 3 is not greater than 20, execution proceeds to line 3 again. A 3 is displayed and Count is incremented by 2 again. This continues until the 10th pass. On this loop iteration, the value ofCount (19) is displayed and Count is incremented to 21. Since Count now exceeds the limit of the test condition (20), the loop is exited.

Example 5.16 Stepping Down

By using a negative value for the loop increment/decrement, we can step backward through a loop. In this case, we are decrementing the counter. That is, we have the counter variable decrease in value from iteration to iteration. For a negative increment, the loop is exited when the value of the counter becomes less than the loop’s limit value.

1 Declare Count As Integer

2 For (Count = 9; Count >=5; Count−2)

3 Write Count

4 End For

The numbers that will be written to the screen if this program segment was coded and run would be 9, 7, and 5.

What Happened?

· Line 2: the counter, Count, is initialized to 9 and the code also says that on each pass through the loop Count will be decreased by 2 until it no longer is greater than or equal to 5.

· Line 3: the initial value of Count, 9, is displayed.

· Next, −2 (the decrement) is added to Count. The value of Count is now 7. Since the limiting value is 5 and Count is still not less than 5, a second pass is done.

· On the second pass, 7 is displayed and Count is decreased to 5. It is still not less than 5, so another pass can be executed.

· Finally, on the third pass 5 is displayed and Count is set equal to 3. Because 3 is less than the limiting value (5), the loop is exited.

Example 5.17 The Prisoner in the Loop

If the loop increment is positive and the initial value is greater than the limiting value, then the body of the loop is skipped as follows:

1 Declare Count As Integer

2 Write "Hello"

3 For (Count = 5; Count < 4; Count++)

4 Write "Help, I'm a prisoner in a For loop!"

5 End For

6 Write "Goodbye"

What Happened?

In this example, the initial value of Count is set to 5 and Count will be incremented by 1 for each iteration of the loop. Unfortunately, the test condition says to execute the loop only while Count is less than 4. Since Count starts out greater than 4, it can never be less than 4 so the body of the loop is skipped. Line 4 will never be executed and whoever is in the loop body is trapped there forever. Thus, the output produced by the code corresponding to this pseudocode is shown as follows:

Hello

Goodbye

The Careful Bean Counter

We round out this section of the chapter with several examples that illustrate some of the pitfalls that can be encountered in both For and While loops. One of the most common errors in a program is using a counter incorrectly. It is the programmer’s decision to pick an initial value, an increment or decrement amount, and a test condition. These choices determine how many times the loop executes. It is very important to check your initial value and test condition value carefully to make sure your loop repeats exactly as many times as you need. With that in mind, we’ll do some bean counting in  Examples  5.18  through  5.24 .

Example 5.18 Count Four Beans

1 Declare Count As Integer

2 Declare Beans as Integer

3 Set Beans = 4

4 For (Count = 1; Count <= Beans; Count++)

5 Write "bean"

6 End For

What Happened?

Let’s see what happens with this program. On the first pass, Count = 1, which is less than Beans (4) and one "bean" is displayed. Then the counter is incremented to 2, which is still less than 4 so a second "bean" is displayed and Count is incremented to 3. This is still less than 4, so the loop repeats, a third "bean" is displayed, and Count is incremented to 4. A fourth "bean" is displayed and Count is incremented to 5. Now Count is greater than Beans (4) so the loop stops. We have displayed four "bean"s, as instructed.

Example  5.19  shows another way to do the same thing.

Example 5.19 Count Four Beans Another Way

1 Declare Count As Integer

2 Declare Beans As Integer

3 Set Beans = 4

4 For (Count = Beans; Count >= 1; Count−−)

5 Write "bean"

6 End For

What Happened?

We begin this program with Count = 4 (the value of Beans). On the first pass, one "bean" is displayed and Count is decremented to 3. Since 3 is greater than1, the loop continues again, a second "bean" is displayed, and Count is decremented to 2. This is still greater than 1, so a third "bean" is displayed andCount is decremented to 1. This passes the test condition because the value of Count is equal to the test condition. A fourth "bean" is displayed and Count is decremented to 0. Now Count fails the test condition and the program ends. We have displayed four "bean"s.

We see how the bean counting is done with a counter-controlled loop using a While loop structure in  Example  5.20 . This program does exactly the same thing as  Example 5.18 .

Example 5.20 Count Four Beans with a While Loop

1 Declare Count As Integer

2 Declare Beans As Integer

3 Set Beans = 4

4 Set Count = 1

5 While Count <= Beans

6 Write "bean"

7 Set Count = Count + 1

8 End While

What Happened?

In this case, after the third loop, when Count = 4, it’s still less than or equal to Beans, so the loop repeats once more and a fourth "bean" is displayed. ThenCount is incremented to 5, and the test condition is no longer true so the program ends, with four "bean"s correctly displayed.

If you aren’t careful, the loop might not execute for the correct number of iterations. It’s important to consider the initial value of the counter as well as the way you write the test condition, as you will see in  Examples  5.21  through  5.24 .

Example 5.21 Use the Test Condition Carefully: Not Enough Beans

This program snippet attempts to display four "bean"s but fails to do so.

1 Declare Count As Integer

2 Declare Beans As Integer

3 Set Beans = 4

4 Set Count = 1

5 While Count < Beans

6 Write "bean"

7 Set Count = Count + 1

8 End While

In this example, a "bean" is displayed and Count, which initially has a value of 1, is incremented to 2. A second "bean" is displayed and Count is incremented to 3. A third "bean" is displayed and Count is incremented to 4. Now Count is not less than Beans so the program ends, but we have only displayed three "bean"s.

For the loop in  Example  5.21  to correctly display four "bean"s, we should have set Count = 0 instead of 1. In  Example  5.22 , we see what happens with a different incorrect limit condition.

Example 5.22 Use the Test Condition Carefully: Too Many Beans

1 Declare Count As Integer

2 Declare Beans As Integer

3 Set Beans = 4

4 Set Count = 0

5 While Count <= Beans

6 Write "bean"

7 Set Count = Count + 1

8 End While

What Happened?

In this case, Count starts at 0, a "bean" is displayed, Count is incremented to 1, and the test condition is true so another pass is executed. The second time around, a second "bean" is displayed and Count is incremented to 2. The test condition is still true. A third "bean" is displayed, Count takes the value of 3, and the test condition is still true. Then the fourth "bean" is displayed and Count gets incremented to 4. But now, when Count = 4, after the fourth "bean" has been displayed, the test condition is still true because Count is still less than or equal to Beans. Therefore, the loop continues for another pass. Now a fifth "bean" is displayed, Count is incremented to 5, and it finally fails the test so the program ends. But we have displayed five "bean"s instead of four.

Example 5.23 Try It Yourself

The following pseudocode would display five "bean"s. Can you see why?

1 Declare Count As Integer

2 Declare Beans As Integer

3 Set Beans = 4

4 Set Count = Beans

5 While Count >= 0

6 Write "bean"

7 Set Count = Count − 1

8 End While

Example 5.24 Try Again

How many "bean"s would the following pseudocode display? Can you figure out what needs to be changed in order to correctly display four "bean"s? You can check your answer; it’s the same as the answer to Self Check Question 5.18.

1 Declare Count As Integer

2 Declare Beans As Integer

3 Set Beans = 4

4 Set Count = Beans

5 While Count >= 0

6 Write "bean"

7 Set Count = Count + 1

8 End While

Before we end this section, we will take a look at the specific syntax of For loops in several programming languages—C++, JavaScript, and Visual Basic. The logic and sequence of execution in all the languages is the same, but the syntax for Visual Basic is quite different from C++ and JavaScript.

 The For Loop

The code in these three languages corresponds to  Example  5.18 .

C++ code:

void main()

{

int Beans = 4;

int Count;

for (Count = 1; Count <= Beans; Count++)

{

cout << "bean";

}

return;

}

JavaScript Code

function main()

{

var Beans = 4;

var Count;

for (Count = 1; Count <= Beans; Count++)

{

document.write("bean");

}

}

Note the similarities between JavaScript and C++!

Visual Basic code:

Private Sub btnBeanCount_Click

Dim Beans as Integer

Dim Count as Integer

Beans = 4

For Count = 1 To Beans Step 1

Write "bean"

Next Count

End Sub

Self Check for Section 5.3

1. 5.13 What numbers will display when code corresponding to the following pseudocode is run?

a. Declare N As Integer

b. Declare K As Integer

c. Set N = 3

d. For (K = N; K <= N+2; K++)

e. Write N + " " + K

f. End For

g. Declare K As Integer

h. For (K = 10; K <= 7; K–2)

i. Write K

j. End For

2. 5.14 What output will display when code corresponding to the following pseudocode is run?

a. Declare N As Integer

b. Declare K As Integer

c. Set N = 3

d. For (K = 5; K >= N; K−−)

e. Write N

f. Write K

g. End For

h. Declare K As Integer

i. For (K = 1; K <= 3; K++)

j. Write "Hooray!"

k. End For

3. 5.15 Write a program (using pseudocode) that contains the statement

For (Count = 1; Count <= 3; Count++)

and that would produce the following output if it were coded and run:

10

20

30

4. 5.16 Rewrite the following pseudocode using a For loop instead of the While loop shown:

5. Declare Number As Integer

6. Declare Name As String

7. Set Number = 1

8. While Number <= 10

9. Input Name

10. Write Name

11. Set Number = Number + 1

End While

12. 5.17 Rewrite the pseudocode of Self Check Question 5.16 using a post-test loop instead of a pre-test loop.

13. 5.18 Find and explain the error(s) in the following pseudocode and then fix the pseudocode to produce an output of four "bean"s if it were run.

14. Declare Beans As Integer

15. Declare Count As Integer

16. Set Beans = 4

17. Set Count = Beans

18. While Count >= 0

19. Write "bean"

20. Set Count = Count + 1

End While

5.4 Applications of Repetition Structures

Throughout the rest of the , you will see many examples of how the repetition (or loop) structure is used to construct programs. In this section, we will present a few basic applications of this control structure.

Using Sentinel-Controlled Loops to Input Data

Loops are often used to input large amounts of data. On each pass through the loop, one item or set of data is entered into the program. A professor teaching a large biology lecture class might use a loop to enter all the grades for an exam. The test condition for such a loop must cause it to be exited after all data has been input. Often the best way to force a loop to end is to have the user enter a special item (a  sentinel value) to act as a signal that input is complete. The sentinel item (or  end-of-data marker) should be chosen so that it cannot possibly be mistaken for actual input data. For example, using the biology professor’s class as an illustration, since all student grades are between 0 and 100, the sentinel value could be the number −1. No student would get −1 for a grade, so when the value of−1 was encountered, the loop would end.  Example  5.25  is a simple example of a  sentinel-controlled loop that uses a sentinel value to determine whether the loop is to be exited.

Example 5.25 A Sentinel-Controlled Loop for Paychecks

Suppose that the input data for a program that computes employee salaries consists of the number of hours worked by each employee and his or her rate of pay. The following pseudocode could be used to input and process this data:

1 Declare Hours As Float

2 Declare Rate As Float

3 Declare Salary As Float

4 Write "Enter the number of hours this employee worked:"

5 Write "Enter −1 when you are done."

6 Input Hours

7 While Hours != −1

8 Write "Enter this employee's rate of pay: "

9 Input Rate

10 Set Salary = Hours * Rate

11 Write "An employee who worked " + Hours

12 Write "at the rate of " + Rate + " per hour"

13 Write "receives a salary of $ " + Salary

14 Write "Enter the number of hours the next employee worked:"

15 Write "Enter −1 when you are done."

16 Input Hours

17 End While

What Happened?

In this program segment, lines 4, 5, and 6 prompt for an initial value of Hours and receive the input to start the loop off. It is crucial that the input prompt makes it clear to the user that the number −1 will signify when all employees have been processed.

If the value input for Hours is the sentinel value −1, then the test condition in the While statement is false, the loop is exited, and input is terminated. Otherwise the loop body is executed, inputting Rate, computing and displaying the salary, and again inputting Hours. Then, the process is repeated. The flowchart shown in  Figure  5.5  illustrates the pseudocode of this example.

Figure 5.5 A sentinel-controlled loop for paychecks

Another way to allow the user to signal that all data have been input is to have the program ask, after each input operation, whether this is the case.  Example  5.26  and the corresponding flowchart shown in  Figure  5.6  show a program segment that illustrates this technique.

Example 5.26 To Know When to Stop, Just Ask

1 Declare Hours As Float

2 Declare Rate As Float

3 Declare Salary As Float

4 Declare Response As String

5 Repeat

6 Write "Enter the number of hours worked."

7 Input Hours

8 Write "Enter the rate of pay: "

9 Input Rate

10 Set Salary = Hours * Rate

11 Write "An employee who worked " + Hours

12 Write "at the rate of " + Rate + " per hour"

13 Write "receives a salary of $ " + Salary

14 Write "Process another employee? (Y or N)"

15 Input Response

16 Until Response == "N"

Figure 5.6 Using a prompt inside a loop instead of a sentinel

Here, the user enters the letter "Y" if there is more data to input or "N" otherwise. Of course, this means the variable Response must be of character or string type. The test condition, Response == "N", then determines whether the loop is reentered.

Data Validation

In  Chapter  4  we discussed defensive programming and how to avoid mathematical pitfalls like dividing by zero or taking the square root of a negative number—two examples of times when data must be validated. You might write a program to accept orders for a small toy business. The customer will enter the number of wind-up mice ordered—one, two, a hundred, or even zero. To ensure that the user does not enter a negative number when entering a quantity of items to order, we use pseudocode similar to the following:

Write "How many wind-up mice do you want to order? −−> "

Input Number

However, despite the input prompt, the user might enter a negative number. Since it’s impossible to sell a negative number of wind-up mice, you must ensure that the user will enter a positive whole number or zero. Therefore, you should include statements in the program that  validate (check) the number input and request a new number if the first number is outside of the accepted range.  Examples  5.27  and  5.28  use loops to accomplish this.

Example 5.27 Validating Data with a Post-Test Loop

Declare MiceOrdered As Integer

Repeat

Write "How many wind-up mice do you want to order? "

Input MiceOrdered

Until MiceOrdered >= 0

This pseudocode validates the number entered using a post-test loop. The prompt

"How many wind-up mice do you want to order?"

is repeated until the number entered (MiceOrdered) is positive.

Example 5.28 Validating Data with a Pre-Test Loop

Sometimes when we validate data, we want to emphasize the fact that the user has made an error by displaying a message to this effect. We can do this with a pre-test loop, as illustrated in the following pseudocode:

1 Declare MiceOrdered As Integer

2 Write "How many wind-up mice do you want to order?"

3 Input MiceOrdered

4 While MiceOrdered < 0

5 Write "You can't order a negative number of mice."

6 Write "Please enter a positive number or zero. "

7 Input MiceOrdered

8 End While

Notice that in validating input data with a pre-test loop, we use two Input statements (and accompanying prompts). The first is positioned before the loop and is always executed; the second is contained within the loop and is executed only if the data entered is not in the proper range. Although this method to validate input data is a little more complicated than that used in  Example  5.27 , it’s also more flexible and user-friendly. Within the body of the data validation loop, you can provide whatever message best suits the situation.

The Int() Function

Sometimes it’s important that the number entered by the user is an integer—a whole number that can be negative, positive, or zero. For example, a shopping cart program written for a website cannot accept orders for noninteger values of the number of items to be ordered. A guessing game program, for example, where the user is asked to guess a number (we will create a game like this in  Chapter  6 ) requires that the guess is an integer. Inputs with fractional parts are not allowed, but such a program could allow positive or negative numbers as well as zero. How such input is validated depends on the programming language.

In this , we will introduce the Int() function to do the job. A  function is a procedure that computes a specified value. We have already used the square root function Sqrt() earlier in the book. That function takes in a number and computes its square root. The  Int() function takes any number and turns it into an integer. Other functions that do almost the same thing are the Floor() and Ceiling() functions, both of which are discussed in this section. Most programming languages include such functions.

The Int() function is written in the form Int(X), where X represents a number, a numeric variable, or an arithmetic expression. The function turns whatever numeric value X has into an integer by discarding the fractional part (if there is any) of the value of X.

If there is a computation to be done inside the parentheses of the Int(X) function, it’s done first. Then the resulting value is turned into an integer. This is what makes Int(X) a function. It has been internally programmed within the programming language, to do whatever steps are necessary to turn a number, a numeric value, or any expression that results in a number into an integer.  Example  5.29  demonstrates how we will use the Int() function.

Example 5.29 The Int() Function

This example demonstrates how the Int() function works on integers, floating point numbers (i.e., numbers with a decimal part), variables, and arithmetic expressions consisting of any combination of these values.

The left side of each of the following expressions takes the numeric values inside the parentheses and makes them into integers, as shown on the right side of each expression:

· Int(53) = 53 → the integer value of an integer is just that integer.

· Int(53.195) = Int(53.987) = 53 → the integer value of a floating point number is just the integer part, with the fractional part discarded.

If we have two variables, Number1 = 15.25 and Number2 = −4.5, then we have the following:

· Int(Number1) = 15 → Number1 represents the value 15.25 and the Int() function turns the value of Number1 into its integer part.

· Int(Number2) = −4 → Number2 represents −4.5 and the integer part of this is −4.

· Int(6 * 2) = 12 → first the Int() function does the math inside the parentheses and then returns the value as an integer.

· Int(13/4) = 3 → 13/4 = 3.25 and the integer part of 3.25 is 3 so Int(13/4) = 3.

· Int(Number1 + 3.75) → = 19 since Number1 = 15.25, the value of 15.25 + 3.75 = 19.00, but the Int() function turns 19.00 (a floating point number) into 19 (an integer).

The Int() function may appear anywhere in a program that an integer constant is valid. For example, if Number is a numeric variable, then each of the following statements is valid:

· Write Int(Number)

· Set Y = 2 * Int(Number − 1) + 5

However, the statement Input Int(Number) is not valid.

Example  5.30  demonstrates how we use the Int() function to validate integer input.

Example 5.30 Using the Int() Function for Data Validation

This program segment uses two loops. First, it checks that the variable we named MySquare entered by the user is actually an integer, and then it uses another loop to display a table of the squares of all integers from 1 to the value of MySquare.

1 Declare MySquare As Integer

2 Declare Count As Integer

3 Repeat

4 Write "Enter an integer: "

5 Input MySquare

6 Until Int(MySquare) == MySquare

7 For (Count = 1; Count <= MySquare; Count++)

8 Write Count + " " + Countˆ2

9 End For

What Happened?

Let’s walk through this program segment, line by line.

· Lines 1 and 2 declare the variables.

· Line 3 begins the first loop.

· Line 4 prompts the user for an integer.

· Line 5 takes in the number the user enters and stores it in a variable named MySquare. Of course, the user can type any number, but for now, let’s pretend the user types 17.5.

· Line 6 checks to see that what the user typed is actually an integer. How does it do this? In our sample situation, the user typed 17.5, so line 6 asks “Is the integer value of MySquare the same as the value of MySquare?” In this case, the answer is no. We know that MySquare = 17.5. We also know thatInt(MySquare) = the integer value of 17.5, which is 17 and is not the same as 17.5. So now the answer to the question asked on line 6 forces the program to go back up to line 3. The user would be prompted again for an integer on line 4. He or she would enter something else and that value would replace the value of 17.5 in MySquare. So let’s pretend that this time the user enters 6. Now we’re back to line 6 again and the test is run again: “Is the value of Int(MySquare) = MySquare?” This time the answer is yes because Int(MySquare) = 6 and MySquare also = 6.

· This first loop will be repeated over and over until the user finally enters an integer and the program moves on.

· Line 7 begins the second loop. It starts with a counter named Count equal to an initial value of 1. Count will be incremented by 1 each pass through this second loop, until it reaches the test value, which is the value of MySquare. In our pretend example, MySquare has the value of 6.

· Line 8 writes the display we want. The first time through this loop, it will display a 1 (the value of Count on the first iteration) and a 1 (the value of Count^2). Then control returns to line 7. Count is now equal to 2, line 8 writes 2 (the value of Count) and 4 (Count^2). This process continues until Count = 6, the value of MySquare.

Notice that the For loop will be executed only if MySquare is greater than or equal to 1. In that case, the table of squares will be displayed; otherwise, the Forloop will be skipped. The result, at the end, assuming that the user entered the integer value of 6 on line 5 is as follows:

1 1

2 4

3 9

4 16

5 25

6 36

The flowchart shown in  Figure  5.7  shows the flow of execution of this program segment and illustrates a flowchart for a program that includes two different types of loops.

What would happen if the user entered −3, a valid integer, on line 5? Nothing would be displayed since the test on line 7 would fail. This program segment will only display the squares of numbers that are greater than zero, even though zero and negative numbers are valid integers with valid squares.

Figure 5.7 Using two types of loops in a program

The Floor() and Ceiling() Functions

Many programming languages have functions which, when used appropriately, can do the same thing as the Int() function. We took a brief look at these functions in the Running With RAPTOR section of the previous chapter and will discuss them in further detail now. The  Floor() function takes any number and turns it into an integer by discarding the decimal part, just as the Int() function has been described in this text. The  Ceiling() function takes any number and rounds it up to the next integer value. While the Ceiling() function would not normally be used to validate integer input, the Floor() function can be used interchangeably with the Int() function for this purpose.

Example 5.31 How the Floor() and Ceiling() Functions Work

This example compares the result of using the Floor() and Ceiling() functions on various values:

Floor(62) = 62 Ceiling(62) = 62

Floor(62.34) = 62 Ceiling(62.34) = 63

Floor(79.89) = 79 Ceiling(79.89) = 80

As with the Int() function, both Floor() and Ceiling() work on numbers, numeric variables, and valid expressions. If we have two variables, NumberOne = 12.2 and NumberTwo = 3.8, then we have the following:

Floor(NumberOne) = 12 Ceiling(NumberOne) = 13

Floor(NumberTwo) = 3 Ceiling(NumberTwo) = 4

Floor(NumberOne * 4) = 48 Ceiling(NumberOne * 4) = 49

The Floor() and Ceiling() functions may appear in a program anywhere an integer constant is valid, just as with the Int() function. If Number is a variable with the value 7.83, the following statements are valid:

· Write Floor(Number) will display 7

· Write Ceiling(Number) will display 8

· Set Y = Floor(Number) assigns the value of 7 to Y

· Set Y = Ceiling(Number) assigns the value of 8 to Y

· Set X = Floor(Number/2) assigns the value of 3 to X

· Set X = Ceiling(Number/2) assigns the value of 4 to X

Example  5.32  demonstrates how we can use the Floor() function to validate integer input.

Example 5.32 Using the Floor() Function for Data Validation

This program segment is based on the pseudocode of  Example  5.28 . In that example a While loop was used to ensure that a customer did not try to order a negative number of wind-up mouse toys. However, the program also needs to ensure that the customer enters an integer value for the number of toys ordered. In this example, we will use the Floor() function to validate integer data. Later, we will see how to validate both positive input and integer input at the same time.

1 Declare MiceOrdered As Integer

2 Write "How many wind-up mice do you want to order? "

3 Input MiceOrdered

4 While Floor(MiceOrdered) != MiceOrdered

5 Write "You must enter a whole number."

6 Input MiceOrdered

7 End While

What Happened?

Line 4 is the point of interest in this example. By comparing Floor(MiceOrdered) with the value of MiceOrdered, we can see if the amount entered was an integer. The only time the Floor() of a number will be the same as that number is when the number is an integer.

 Validating More than One Condition

Example  5.32  only checks to see if the value entered is an integer. However, negative values like −3 or −12 are integers and are not valid entries for a customer’s order. The program must check two things: is the value entered an integer? And is that integer not negative? Can you think of a way to combine these two conditions in one loop?

This can be done with a compound condition, using logical operators. While there is always more than one way to solve this type of problem, see if you can rewrite the program segment using the following single compound condition:

While (Floor(MiceOrdered) != MiceOrdered) OR (MiceOrdered <= 0)

Example 5.33 Using the Ceiling() Function for a Pay Raise

Kim Smart works for a small business doing the payroll. She noticed that the payroll program her boss used was set up to pay hourly employees only in full-hour increments. Thus, a person who worked 25.2 hours as well as a person who worked 25.9 hours would both get paid for only 25 hours. The previous programmer had used the Int() function to convert floating point numbers to integer values. Kim decided that the previous programmer was probably unaware of the fact that this method would always underpay a worker unless the worker put in an exact integer value for the number of hours worked. Kim fixed the situation by using the Ceiling() function and hoped that her boss would not notice that now most employees were getting a better deal. In the following program segment, we see how this is done. Notice also that Kim used a compound condition to validate the input of both the number of hours worked and the pay rate.

1 Declare Hours As Float

2 Declare Rate As Float

3 Declare Pay As Float

4 Write "Enter number of hours worked: "

5 Input Hours

6 Write "Enter hourly pay rate: "

7 Input Rate

8 While (Hours < 0) OR (Rate < 0)

9 Write "Negative values are not allowed."

10 Write "Re-enter number of hours worked: "

11 Input Hours

12 Write "Re-enter hourly pay rate: "

13 Input Rate

14 End While

15 Set Pay = Ceiling(Hours) * Rate

16 Write "The pay for this employee is $ " + Pay

What Happened?

There are two lines of particular interest in this program segment. Line 8 is the compound condition. Because OR is used, the While loop will be entered if eitherHours or Rate have been input as negative numbers. In this program segment, the user is required to re-enter both values (Hours and Rate) even if only one value was originally entered incorrectly. Later in the text, we will discuss methods to make this duplication unnecessary.

Line 15 uses the Ceiling() function within a calculation. This is a valid use of a function; it can be used anywhere that an integer value is acceptable. For example, if Hours was entered as 36.83 and Rate was entered as 9.50, the statement on line 15 would do the following:

First, Ceiling(Hours) would be evaluated: Ceiling(36.83) = 37. Then, this value would be multiplied by Rate (9.50) and the result, 351.50, would be stored in Pay.

Computing Sums and Averages

You may wonder why it is so important to discuss how sums and averages are computed in a program. It is not immediately obvious to someone new to programming how often programs use summing, but sums are used for many purposes other than simply adding numbers.

Computing Sums

Computers compute sums by using an  accumulator, which is a variable that holds the accumulated result. The process of accumulating a value is used over and over in many computer programs. To use a calculator to sum a list of numbers, you add each successive number to the running total. In effect, you are looping because you are repeatedly applying the addition operation until all the numbers have been added. To write a program to sum a list of numbers, you do essentially the same thing, as illustrated in  Example  5.34 .

Example 5.34 Using a Loop to Compute a Sum

The following pseudocode adds a list of positive integers entered by the user. It uses 0 as a sentinel value. This number is entered by the user to indicate that input is complete.

1 Declare Sum As Integer

2 Declare Number As Integer

3 Set Sum = 0

4 Write "Enter a positive number. Enter 0 when done: "

5 Input Number

6 While Number > 0

7 Set Sum = Sum + Number

8 Write "Enter a positive number. Enter 0 when done: "

9 Input Number

10 End While

11 Write "The sum of the numbers input is " + Sum

What Happened?

In this program segment, we have a variable named Sum. In this context, such a variable is called the accumulator, which makes sense since it  accumulates all the numbers. When the loop is finished, the accumulator, Sum, contains the sum of all the numbers entered and the sum is displayed. A flowchart for this example is shown in  Figure  5.8  . Notice that the test condition in the flowchart tests if Number is the same as 0, while the pseudocode in this example checks if Number is greater than 0. Both tests work but the test in our pseudocode (Number > 0) guards against negative input.

Figure 5.8 Using an accumulator to sum numbers

To understand how this algorithm works, let’s trace execution of this pseudocode if input consists of the numbers 3, 4, 5, and 0:

· Lines 1 and 2 define the variables, Sum and Number. Prior to entering the loop, we initialize the variable Sum to 0 (line 3) so that it will not be an undefined variable when the right side of the statement on line 7 (Set Sum = Sum + Number) is evaluated. For the same reason, we input the initial value of Numberfrom the user prior to entering the loop.

· Lines 4 and 5 ask for and obtain the first value of Number.

· Line 6: On the first pass through the loop Number equals 3, so the test condition is true and the loop body is executed.

· Line 7: The current values of Sum and Number are added. Before the addition is performed, the values are 0 and 3. After the addition is performed Sum = 3.

· Lines 8 and 9: The next number is requested and 4 is input and assigned to Number. The old value of Number (3) is lost.

· A second pass is now made through the loop in which Number = 4 and this value is added to the current running total (3) to increase the value of Sum to 7. In this pass, the number 5 is input and now Number = 5.

· Since Number is still not 0, the loop body is executed once more. The new value of Sum is the previous value (7) plus the new value of Number (5), or 12.

· Another number is requested and input. This time the user enters 0.

· Now Number is 0, so the test condition is false. The loop is exited and the current value of Sum, 12, is displayed.

 Initialize Your Variables

When a variable is declared in a program, it’s always a good idea to give it an initial value. When you declare a variable you are actually setting aside a space in the computer’s memory as a storage space. That space may be empty, or it may have a value left over from some previous command or variable that is no longer being used. In  Example  5.34  we have a variable named Sum. If we did not initialize it to equal 0 and, by a stroke of bad luck, the storage space the computer assigned to Sum had a value of 186 left in it by a previous program statement, then our sum would begin withSum = 186. And our answer would be incorrect. To avoid this and other problems that may arise when variables are declared, it’s best to make sure that they have the value you want them to start with by simply setting them to that value at the time you declare them.

Computing Averages

To calculate the average (or mean) of a list of numbers, we compute their sum and divide that sum by the number of data items in the list. Thus, the process of finding an average is similar to that of finding a sum, but here we also need a counter to keep track of how many numbers have been entered.  Example  5.35 shows the pseudocode for finding the mean of a list of positive numbers.

Example 5.35 Computing Your Exam Average

Now that you understand a little about programming, you might want to write a program to calculate various averages in the courses you are taking this semester. The following program pseudocode shows how. Because we use variables and a sentinel-controlled loop, you can reuse this code to calculate your average in each of your courses. It doesn’t matter if you have 3 exams or 33 exams. When this pseudocode is turned into real program code, it can be used again and again.

1 Declare CountGrades As Integer

2 Declare SumGrades As Float

3 Declare Grade As Float

4 Declare ExamAverage As Float

5 Set CountGrades = 0

6 Set SumGrades = 0

7 Write "Enter one exam grade. Enter 0 when done."

8 Input Grade

9 While Grade > 0

10 Set CountGrades = CountGrades + 1

11 Set SumGrades = SumGrades + Grade

12 Write "Enter an exam grade. Enter 0 when done."

13 Input Grade

14 End While

15 Set ExamAverage = SumGrades/CountGrades

16 Write "Your exam average is " + ExamAverage

What Happened?

· Lines 1–6 declare and initialize the variables.

· Line 7 asks for the first exam grade and also explains that when you are finished entering the exam grades for a particular set, you can end by entering 0.

· The first grade is input on line 8.

· Lines 9–14 are the loop. In this example, we used a While loop, which does two things—it sums the grades entered and it keeps count of how many grades were entered.

· On Line 10 we keep track of how many grades are entered. For each pass through the loop, CountGrades is incremented by 1. If you enter three grades before you end the program by entering 0, the loop will execute three times and CountGrades will be equal to 3. If you enter 68 grades, the loop will execute 68 times and CountGrades will be equal to 68.

· Line 11 keeps a sum of all the exam scores. To compute your exam average, you must divide the sum of all your exam grades by the number of exams, so lines 10 and 11 keep track of the information we need to compute the average at the end.

· Lines 12 and 13 ask the user for the next exam grade and gets the next input. Here, if you’re done, you can enter a 0.

· Line 14 ends the loop when the user enters a zero.

· Line 15 computes the average and line 16 displays that average.

In  Example  5.35 , what would happen if your four exam grades for your basket weaving class were 0, 98, 96, and 92? The first grade you would enter would be 0. Line 9 says to do the loop only while Grade > 0. So the loop would never be executed, even though you would actually have an exam average in this class. Furthermore, if any student grade was 0, the loop would exit and this would exclude the student’s other grades. How could you change the test condition on line 9 to take this situation into account?

And what would happen on line 15? If the first exam grade was 0, the loop would not execute and the program would jump to line 15. The value ofSumGrades is 0 and the value of CountGrades is also 0. Then the statement:

ExamAverage = SumGrades/CountGrades

would try to execute but a “division by zero” error would occur.

We showed how to avoid this situation using defensive programming techniques in  Chapter  4 . To rewrite this program so that it allows for an initial grade of 0 and also checks to be sure that the “division by zero” error does not occur, you may want to include an If-Then statement inside a loop.This process is covered in detail in  Chapter  6 .

Self Check for Section 5.4

1. 5.19 Write pseudocode using a post-test loop that inputs a list of characters from the user until the character * (an asterisk) is input.

2. 5.20 Suppose you want to input a number that should be greater than 100. Write pseudocode that validates input data to accomplish this task in the following two ways:

a. Using a pre-test (While) loop.

b. Using a post-test (Repeat . . . Until or Do . . . While) loop.

3. 5.21 Give the number displayed by each of the following statements:

a. Write Int(5)

b. Write Int(4.9)

4. 5.22 Give the number displayed by each of the following statements:

a. Write Floor(3.9)

b. Write Floor(786942)

c. Write Ceiling(3.9)

d. Write Ceiling(2 * 3.9)

5. 5.23 Given the following values of the variables, what is stored in NewNum?

X = 4.6 Y = 7 Z = 0

a. Set NewNum = Int(X) + Ceiling(Y)

b. Set NewNum = Floor(X * Z)

c. Set NewNum = Int(Z) – Y

6. 5.24 Use a For loop to sum the integers from 1 to 100.

7. 5.25 Modify the program of Self Check Question 5.24 so that it finds both the sum and the average of integers from 1 to 100.

chapter 6.docx

More about Loops and Decisions

In this chapter, we continue to explore the topic of repetition structures. We will discuss how loops are used in conjunction with the other control structures—sequence and selection—to create more complex programs. We continue the discussion of different types of loops, including using loops for data validation, using nested loops, and using loops for data input.

After reading this chapter, you will be able to do the following:

· Create and use loops with selection structures

· Apply loops to data input problems

· Combine loops with Select Case statements

· Understand how to create output on separate lines with a newline indicator

· Include random numbers in loops by using the Random() function

· Create and use nested loops

In the Everyday World Loops Within Loops

In  Chapter  5  you learned how to create various types of simple loops. A loop was compared to the process of learning to walk—putting one foot in front of the other over and over and over. When you walk across a room, you are completing the “put one foot in front of the other” loop many times. But you may be walking across the room to pick up a book you need to complete a homework problem. So you do the “put one foot in front of the other loop” until you get to your bookcase. Then you search for your book and, after you find it, you turn around and do the “put one foot in front of the other” loop again until you get back to your desk. In this chapter, you will learn various ways to use loops within longer programs or to solve more complex problems. This is done by combining loops with the other control structures that we have learned.

Loops are often combined with other loops by putting one loop inside the other. Imagine, for now, that you work as a bagger in a grocery store. It is your job to fill bags with groceries while the cashier rings up a purchase. So you put one grocery item after another into one bag until that bag is full, then you fill another bag, and another until a customer’s order is done. This is an example of a loop inside a loop. For a single customer, this situation can be expressed as follows:

Repeat

Open a grocery bag

While there is room in the bag

Place an item in the bag

End While

Place filled bag in the customer's grocery cart

Until all the customer's groceries have been bagged

In fact, you could put these two loops inside a larger outer loop to continue the whole process for many customers until your shift ends. Or you could include a decision statement within the outer loop, which would allow you to stop the process if it is time for a lunch break.

6.1 Combining Loops with If-Then Statements

Early in this textbook you learned that virtually all computer programs are composed of code written using the three control structures: sequence, selection, and repetition. Now that we have learned about each of these structures separately, we can put them together to form programs that do everything from displaying a greeting on the screen to creating a word processor to performing calculations for a space ship to travel to Mars.

We have already combined selection structures and repetition structures with the sequence structure. In this section, we will combine repetition structures and selection structures. We’ll begin by showing you how to use an If-Then structure within a loop. This will allow the loop to end, if necessary, before it completes all the iterations specified in the test condition.

Exiting a Loop

It’s possible to break out of a loop if the user has entered an incorrect value that would cause an error or a problem within the loop, or if the user has entered a required response and the program can continue without further iterations.  Examples  6.1  and  6.2  demonstrate these situations.

Example 6.1 Exiting the Loop When There’s No More Money 1

1 To create programs in RAPTOR that are shown in this text with For loops, refer to the flowcharts that correspond with the examples. RAPTOR uses the same logic for a For loop as a While loop.

In this program segment pseudocode, you will imagine that you have a specific amount of money to spend. You’re shopping online, and this program segment will keep track of the cost of your purchases and let you know when you have either reached your spending limit or bought 10 items. At the end, the program will display your exact purchase amount. The pseudocode uses a new statement, Exit For, to kick us out of the “purchasing loop” if the spending limit is exceeded. When an Exit For statement is encountered, the statement following the end of the For loop (the one after End For) is executed next. The flowchart that corresponds to this pseudocode is shown in  Figure  6.1 .

1 Declare Cost As Float

2 Declare Total As Float

3 Declare Max As Float

4 Declare Count As Integer

5 Set Total = 0

6 Write "Enter the maximum amount you want to spend: $ "

7 Input Max

8 For (Count = 1; Count < 11; Count++)

9 Write "Enter the cost of an item: "

10 Input Cost

11 Set Total = Total + Cost

12 If Total > Max Then

13 Write "You have reached your spending limit."

14 Write "You cannot buy this item or anything else."

15 Set Total = Total − Cost

16 Exit For

17 End If

18 Write "You have bought " + Count + " items."

19 End For

20 Write "Your total cost is $ " + Total

Figure 6.1 Flowchart using an If-Then structure within a loop to allow an early exit

What Happened?

· Lines 1–7 declare the necessary variables (Cost, Total, Max, and Count) and allow the user to input the maximum amount to spend.

· The For loop begins on line 8 and allows the user to input up to ten items.

· Lines 9 and 10 prompt for and input the cost of one item.

· Line 11 keeps a total of the cost of all the items.

· Line 12 uses an If-Then structure to check if the user has spent over the limit. If the last item entered puts the user over the limit, lines 13–16 are executed. The user receives a message that this last item costs too much to buy and that the spending limit has been reached (lines 13 and 14).

· Line 15 subtracts off the cost of the last item from the total since this item cannot be bought.

· Line 16 exits the loop and control proceeds to line 18, which tells the user how many items he has purchased and then, on line 20, displays the total up to, but not including, the cost of the last item entered. In general, if an Exit For statement is encountered in a For loop, control is immediately transferred to the program statement that follows End For. The exact syntax to accomplish this will differ, of course, from one programming language to the next, but the result will be the same; the loop is exited early.

· However, if an item entered does not put the total cost over the spending limit—that is, if the answer to the question on line 12 is "no" (Total is not greater than Max)—then the Then-clause is never executed and the next step is line 18. This displays the number of items purchased so far. Control returns to line 8 where Count is incremented and then checked to see if the user has entered 10 items.

· The program ends when the user enters 10 items or when the user enters fewer than 10 items and the total cost is greater than Max, whichever comes first.

Next, we’ll look at how to use an If-Then-Else structure within a loop for  data validation. The loop continues only while the user enters appropriate data. In this example, the appropriate data is an integer, and the loop is exited if the entry is not an integer.

Example 6.2 Summing Integers and Only Integers

This program segment pseudocode asks the user to enter 10 integers and computes their sum. The loop ends when the user has entered all 10 integers or exits early if the user enters a noninteger value. To accomplish this, we make use of the If-Then-Else structure and the Int() function. A flowchart corresponding to this example is shown in  Figure  6.2 .

1 Declare Count As Integer

2 Declare Sum As Integer

3 Declare Number As Float

4 Set Sum = 0

5 For (Count = 1; Count <=10; Count++)

6 Write "Enter an integer: "

7 Input Number

8 If Number != Int(Number) Then

9 Write "Your entry is not an integer."

10 Write "The summation has ended."

11 Exit For

12 Else

13 Set Sum = Sum + Number

14 End If

15 End For

16 Write "The sum of your numbers is: " + Sum

What Happened?

· Lines 1–7 declare the three variables (Count, Number, and Sum), initialize Sum, begin the For loop, and accept a number from the user. By declaring Numberas a Float, we have allowed the user to enter any number. However, the prompt asks for an integer so we must test (on line 8) to make sure the user has followed the directions.

· In line 8, the number the user entered is tested. Recall that the Int() function turns any number, Float or Integer, into the integer value of that number. Therefore, if the user enters 5.38 for Number, the value of Int(Number) will be 5. In this case, the result of the test on line 8 will be true. The value ofNumber (which is 5.38) will not be the same as the value of Int(Number) (which is 5). Thus, the next lines to be executed will be lines 9 and 10.

· The user will see the following display:

· Your entry is not an integer.

The summation has ended.

· Line 11 will force the loop to end. As mentioned in the previous example, the exact syntax to accomplish this will differ from language to language, but the result will be the same. When the user has entered a noninteger value, the loop will not complete all 10 iterations.

· However, if the user entered the number 4 on line 7, then the value of Int(Number) on line 8 would be exactly the same as the value of Number. Since the test on line 8 would return a value of false, the Then clause of the If-Then-Else statement would not be executed. Control would jump to line 12, the Elseclause.

· The summation would continue on line 13. Then control would return to the top of the For loop and another number would be entered.

· This will continue until one of two things happens—either the user enters a noninteger number or the user enters 10 integers. Line 16 will be executed regardless of which of the two events occurs.

Since the Floor() function also converts a floating point number to an integer by dropping the fractional part of the number, it can be substituted for Int() in this program and anywhere else that Int() appears in program segments in the text.

There is one more thing to mention about this pseudocode. If a user entered any nonnumeric character on line 7, in most programming languages the program would stop or display an error message. However, the purpose of this example is to demonstrate how to validate numeric input so, for now, we will not address the possibility of a nonnumeric entry.

Figure 6.2 Flowchart using an If-Then-Else structure inside a loop to validate data input

Notice that, in  Example  6.2 , the test condition states that the loop should continue while Count <= 10. In  Example  6.1 , the test condition stated that the loop should continue while Count < 11. Since, in both examples, Count is incremented by 1 during each pass, both of these conditions will require the loop to complete 10 iterations. The decision about how to write the test condition, in these cases, is simply a matter of programmer preference.

In a For loop, the counter is incremented or decremented, by default, after the loop body is executed but before the test condition is tried again (i.e., at the bottom of the loop body). In a Repeat . . . Until, Do . . . While, or While loop, the placement of the increment or decrement of the loop is up to the programmer. The decision about what to use as a test condition is then based on the desired outcome. The following four little program segments create different displays because of the placement of the counter increment and the value of the test condition:

Set Count = 1

While Count <= 3

Write Count + "Hello"

Set Count = Count + 1

End While

Display

1 Hello

2 Hello

3 Hello

Set Count = 1

While Count <= 3

Set Count = Count + 1

Write Count + "Hello"

End While

Display

2 Hello

3 Hello

4 Hello

Set Count = 1

While Count < 3

Write Count + "Hello"

Set Count = Count + 1

End While

Display

1 Hello

2 Hello

Set Count = 1

While Count <= 2

Set Count = Count + 1

Write Count + "Hello"

End While

Display

2 Hello

3 Hello

Clearly, the choice of the test condition, combined with the placement of the counter increment is extremely important when writing loops that work exactly as they are supposed to work!

Now that you are adept at programming, you have decided to write a guessing game program for your friend’s children. One child will input a secret number and the other will attempt to guess that number. In  Example  6.3 , we will simply use the words Clear Screen to signify that the screen will be cleared as soon as the secret number is entered.

Example 6.3 A Simple Guessing Game

The pseudocode in this example shows how to develop a simple guessing game. One person inputs a secret number and the second person must guess that number. As soon as the first person enters a secret number, the Clear Screen statement will clear the screen so the second person cannot see the number. While the syntax for this command differs from language to language, every programming language has a way to hide user entries immediately, as you may have seen when entering a password into a website.

The problem you face when creating this game is that there are a great many numbers in the world. If you allow the user who is guessing the secret number to keep guessing until he or she is correct, the game could go on for a very, very long time. So you decide to allow the user five chances to guess the secret number. Therefore, your loop must allow five guesses, or if the person guesses correctly before the fifth try, the loop must be exited. A flowchart corresponding to this example is shown in  Figure  6.3 . The pseudocode for this little game is as follows:

1 Declare SecretNumber As Integer

2 Declare Count As Integer

3 Declare Guess As Integer

4 Write "Enter a secret number: "

5 Input SecretNumber

6 Clear Screen

7 For (Count = 1; Count <= 5; Count++)

8 Write "Guess the secret number: "

9 Input Guess

10 If Guess == SecretNumber Then

11 Write "You guessed it!"

12 Exit For

13 Else

14 Write "Try again"

15 End If

16 End For

Figure 6.3 Flowchart using an If-Then-Else structure inside a loop for a guessing game

The first three examples in this chapter used For loops in combination with If-Then or If-Then-Else statements. However, any type of loop can be combined with selection statements, as we will see in  Examples  6.4  and  6.5 .

Example 6.4 The Guessing Game Repeats

In this example, we will rewrite the pseudocode of  Example  6.3  using a Do . . . While post-test loop. The Exit statement on line 13 functions as the Exit For statement did in previous examples. It allows the program control to pass immediately to whatever comes immediately after the end of the loop.

1 Declare SecretNumber As Integer

2 Declare Count As Integer

3 Declare Guess As Integer

4 Write "Enter a secret number: "

5 Input SecretNumber

6 Clear Screen

7 Set Count = 1

8 Do

9 Write "Guess the secret number: "

10 Input Guess

11 If Guess == SecretNumber Then

12 Write "You guessed it!"

13 Exit

14 Else

15 Write "Try again"

16 End If

17 Set Count = Count + 1

18 While Count <= 5

Before we end this section, we will write one more program using a While loop combined with an If-Then-Else statement for data validation. In  Example  6.5 , we write pseudocode for a program that will compute the square root of a number and display that result. Recall from  Chapter  4  that most programming languages contain a function that computes square roots and, in this text, we have defined that function to be Sqrt(). Also, as you know, Sqrt() can only compute the positive square root of a positive number. Therefore, the program will have to test the input to ensure that only positive numbers are entered.

Example 6.5 Computing Valid Square Roots with a While Loop

This program segment uses a While loop to allow the user to find the square roots of as many positive numbers as desired and an If-Then-Else statement to validate data input.

1 Declare Number As Float

2 Declare Root As Float

3 Declare Response As Character

4 Write "Do you want to find the square root of a number?"

5 Write "Enter 'y' for yes, 'n' for no: "

6 While Response == "y"

7 Write "Enter a positive number: "

8 Input Number

9 If (Number >= 0) Then

10 Set Root = Sqrt(Number)

11 Write "The square root of " + Number + " is: " + Root

12 Else

13 Write "Your number is invalid."

14 End If

15 Write "Do you want to do this again?"

16 Write "Enter 'y' for yes, 'n' for no: "

17 Input Response

18 End While

Self Check for Section 6.1

1. 6.1 Redo the pseudocode for  Example  6.4  to ensure that the input (the user’s Guess) is a valid integer.

2. 6.2 True or False? If-Then-Else statements can only be combined with For loops.

3. 6.3 True or False? It is not possible to put a loop inside an If-Then statement.

4. 6.4 If NumberX= 3 and NumberY = 4.7 determine whether each of the following statements is true or false:

a. NumberX = Int(NumberX)

b. NumberY = Int(NumberY)

5. 6.5 If NumberX = 6.2, NumberY = 2.8, and NumberZ = 9, determine whether each of the following is true or false:

a. NumberZ = Floor(NumberX + NumberY)

b. NumberZ = Floor(NumberZ)

6. 6.6 The following pseudocode allows the user to enter up to 10 numbers and see those numbers displayed on the screen. It contains one error. Identify the error and fix it.

7. Declare Count As Integer

8. Declare Number As Integer

9. Declare Response As String

10. For (Count = 1; Count < 10; Count++)

11. Write "Enter a number: "

12. Input Number

13. Write "The number you entered is: " + Number

14. Write "Do you want to continue?"

15. Write "Enter 'y' for yes, 'n' for no:"

16. Input Response

17. If Response == "n" Then

18. Write "Goodbye"

19. Exit For

20. End If

End For

6.2 Combining Loops and Decisions in Longer Programs

In this section, we will use loop structures combined with If-Then structures to create several longer and more complex program segments.

Example  6.6  shows how we can keep track of how many positive numbers and how many negative numbers are input by a user. A program segment such as this could be embedded in a larger program, with modifications, to keep track of various types of entries. For example, a college might enter demographic information on students and want to keep track of how many students are older than a certain age. A business might want to track how many items a user purchased that are above or below a certain cost.

Example 6.6 Keeping Track of User Inputs

This program segment inputs numbers from the user (terminated by 0) and counts how many positive and negative numbers have been entered. A flowchart for this program segment is shown in  Figure  6.4 .

1 Declare PositiveCount As Integer

2 Declare NegativeCount As Integer

3 Declare Number As Integer

4 Set PositiveCount = 0

5 Set NegativeCount = 0

6 Write "Enter a number. Enter 0 when done: "

7 Input Number

8 While Number != 0

9 If Number > 0 Then

10 Set PositiveCount = PositiveCount + 1

11 Else

12 Set NegativeCount = NegativeCount + 1

13 End If

14 Write "Enter a number. Enter 0 when done: "

15 Input Number

16 End While

17 Write "The number of positive numbers entered is " ↵ + PositiveCount

18 Write "The number of negative numbers entered is " ↵ + NegativeCount

What Happened?

· Lines 1–5 declare and initialize the counters, PositiveCount and NegativeCount.

· Lines 6 and 7 ask for and accept input of the first number, Number, from the user.

· The loop begins on line 8 and continues iterations as long as Number is not 0.

· Then within the loop, each number that has been entered is examined by the If-Then-Else structure.

· Line 9 checks to see if the number is positive.

· If this is true, the Then clause on line 10 is executed. PositiveCount is incremented by one so this keeps track of how many positive numbers have been entered.

Figure 6.4 Using selection structures with loops to keep track of counts

· If the number is negative, the Else clause on lines 11 and 12 are executed and NegativeCount is incremented by one, keeping track of how many negative numbers have been entered. Remember, in an If-Then-Else structure, when the If statement is true, the Else clause is skipped.

· Line 13 ends the If-Then-Else clause.

· Since any number entered must be positive, negative, or zero, all possibilities have been accounted for. The program continues to line 14 where the user is prompted for another number.

· The next number is input (line 15) and control returns to line 8 where the number is checked to see if it is zero. If it is not zero, the loop goes through another pass.

· If the number is zero, the loop is exited and PositiveCount and NegativeCount contain, respectively, the total number of positive and negative numbers entered. Control goes to lines 17 and 18 where the results of the positive and negative counts are displayed.

Example  6.7  combines Select Case statements with a loop in a longer program segment that might be used by a business.

Example 6.7 Keeping Track of Shipping Costs

Today, everyone who opens a small business must have an online presence. Customers expect to order from websites so online businesses need a program to calculate costs. In this example, we will use a loop and two Select Case statements to allow a customer to order as many items as desired. The business owner can offer various discounts to the customer, based on the cost of items. Shipping costs and sales tax will also be calculated, based on the total cost of the purchase. The shipping cost is dependent on the total amount purchased, while tax is calculated at a single rate. In our example, the discounts will be as shown but it would take very little work to alter the program for different discounts, shipping costs, and tax rates.

· The tax rate for our program is 6%.

· Discounts are offered as follows:

· Items that cost $20.00 or less receive a 10% discount.

· Items that cost between $20.01 and $50.00 receive a 15% discount.

· Items that cost between $50.01 and $100.00 receive a 20% discount.

· Items that cost over $100.00 receive a 25% discount.

· Shipping costs are calculated on the total purchase price and are as follows:

· If the total purchase is $20.00 or less, shipping is $5.00.

· If the total purchase is between $20.01 and $50.00, shipping is $8.00.

· If the total purchase is between $50.01 and $100.00, shipping is $10.00.

· Purchases over $100.00 receive free shipping.

The pseudocode for this program is as follows:

1 Declare ItemCost As Float

2 Declare ItemTotal As Float

3 Declare Tax As Float

4 Declare Ship As Float

5 Declare Count As Integer

6 Declare NumItems As Integer

7 Declare TotalCost As Float

8 Set ItemTotal = 0

9 Set TotalCost = 0

10 Write "How many items are you buying? "

11 Input NumItems

12 For (Count = 1; Count <= NumItems; Count++)

13 Write "Enter the cost of item " + Count

14 Input ItemCost

15 Select Case Of ItemCost

16 Case: <= 20.00

17 Set ItemCost = ItemCost * .90

18 Break

19 Case: <= 50.00

20 Set ItemCost = ItemCost * .85

21 Break

22 Case: <= 100.00

23 Set ItemCost = ItemCost * .80

24 Break

25 Case: > 100.00

26 Set ItemCost = ItemCost * .75

27 Break

28 End Case

29 Set ItemTotal = ItemTotal + ItemCost

30 End For

31 Select Case Of ItemTotal

32 Case: <= 20.00

33 Set Ship = 5.00

34 Break

35 Case: <= 50.00

36 Set Ship = 8.00

37 Break

38 Case: <= 100.00

39 Set Ship = 10.00

40 Break

41 Case: > 100.00

42 Set Ship = 0.0

43 Break

44 End Case

45 Set Tax = ItemTotal * 0.06

46 Set TotalCost = ItemTotal + Tax + Ship

47 Write "Your item total is $ " + ItemTotal

48 Write "Shipping costs will be $ " + Ship

49 Write "The total amount due, including sales tax,"

50 Write " is $ " + TotalCost

What Happened?

· Lines 1 through 9 declare and initialize the variables needed for the program. The variables that refer to costs (ItemCost, ItemTotal, Tax, Ship,TotalCost) are floating point variables since prices usually include both dollars and cents. The variables Count and NumItems are integer variables.

· Lines 10 and 11 prompt for and input the number of items the customer wishes to buy. This variable, NumItems, will be used as the test condition in the loop.

· The loop begins on line 12 and continues iterations as long as the counter is not greater than the number of items the customer is buying.

· Lines 13 and 14 allow the customer to input the cost of an item.

· Lines 15 through 28 constitute the first Select Case statement. Here is where the discount is applied. For example, a 10% discount is achieved by finding 10% of the amount and subtracting it from the amount, as shown:

ItemCost − 0.10 * ItemCost = 0.90 * ItemCost

So, for a 10% discount, what is really needed is 90% of ItemCost. This pseudocode avoids the extra step and simply calculates 90% of the ItemCost. Similarly, for a 15% discount, 85% of ItemCost is the same as subtracting 15% from the amount.

· You will recall how a Select Case statement works: if ItemCost matches the first Case (i.e., ItemCost is less than or equal to 20.00), line 17 will be executed and, due to the Break statement on line 18, the remaining lines of code in this Select Case statement (lines 19–27) are skipped. If, however, an item costs, for example, $98.52, its value is checked on line 16 and, since it does not match this Case, lines 17 and 18 are skipped. Then the value is checked on 19 and, once again, it does not match this Case so lines 20 and 21 are skipped. However, this ItemCost does fall in the range of the Casespecified on line 22 so line 23 is executed. The Break statement on line 24 forces lines 25–27 to be skipped as soon as a Break statement is encountered. In other words, with a Select Case statement, only the instructions following the matching Case are executed and all the other instructions are skipped. Therefore, the cost of each item is checked and, depending on that cost, the appropriate discount is applied. The discounted price of the item is now stored inItemCost until the loop repeats and a new item’s cost is entered.

· Line 29 keeps a sum of the total cost to the consumer. After calculating this total, control is returned to the top of the For loop. If Count is still not greater than NumItems, another ItemCost is entered on line 14 and the discount is applied to that item.

· When all the items have been entered, discounted, and added to the total cost, the For loop is exited (line 30).

· Lines 31 through 44 calculate the shipping cost, based on the total price of the purchase. In this program, we use another Select Case statement for this task.

· Line 45 computes the tax based on the total cost of the items, not including shipping costs, at a rate of 6%.

· Line 46 computes the total cost to the customer, including tax and shipping.

· Lines 47–50 display the results to the customer.

Can you think of ways to improve this program? There are several things that could be added or changed, which would increase the usability of the program. Computers calculate floating point numbers to many decimal places. If this program was coded in a real programming language, the output would be formatted so that costs are displayed with only two decimal places.

Data validation code should also be added to ensure that the customer enters a positive integer value for the number of items to purchase. A suitable message should be displayed if the customer enters 0 for the number of items to purchase. A prompt should be added if the customer enters a noninteger value or a negative number to check if the customer made an error in typing or if the customer truly wants to exit the program.

The program would also be more useful if the tax rate was assigned to a variable. That way, if the tax rate changed at a future date, the business owner could simply change the value of that variable instead of searching through the code for all the places where the tax rate was used.

In fact, it is always better to write code that can be used in the most general case. In the pseudocode of this example, the discount rates are set specifically to be 10%, 15%, 20%, and 25%. Shipping costs are also set specifically to be $5.00, $8.00, $10.00, or free. Can you think of how to write this program to make these items less specific and, therefore, easier for a user to change if necessary?

You will explore these possibilities in the Self Check questions.

The Length_Of() Function

We have already used the Length_Of() function in a RAPTOR program earlier in the text. Here, we will review how that function works for those who are not using RAPTOR with this book . Most programming languages contain a built-in function that is similar to the  Length_Of() function . This function accepts a value inside the parentheses and returns a different value to the variable assigned to the result. The Length_Of() function takes a string or a string variable inside the parentheses and returns the number of characters in that string, as demonstrated in  Example  6.8 .

Example 6.8 The Length_Of() Function

This example demonstrates how the Length_Of() function works on strings. Since the Length_Of() function returns an integer, the variable on the left side of each expression must be an integer variable. In the following examples, it is to be assumed that MyLength has been declared as an integer.

· MyLength = Length_Of("Hello") assigns the value of 5 to MyLength because Hello has five characters.

· MyLength = Length_Of("Good-bye!") assigns the value of 9 to MyLength because the string has nine characters, including the hyphen and exclamation point.

· If Name = "Hermione Hatfield" then:

MyLength = Length_Of(Name) assigns the value of 17 to MyLength

· If TheSpace = " ", then:

MyLength = Length_Of(TheSpace) assigns the value of 1 to MyLength because a space is counted as one character

The Print Statement and the New Line Indicator

At this point we will introduce a new pseudocode statement: the  Print statement . In the pseudocode that we have used so far, the Write statement indicates output to the screen with the assumption that each new Write statement would begin on a new line. In most programming languages, output will be displayed in one continuous line on the screen unless the programmer specifically instructs the program to go to the next line. The code to indicate a new line varies from language to language, but the result is the same: to get output on separate lines; the programmer must indicate this to the computer in one form or another. For some problems discussed in this chapter and later in the text, the Write statement is not a realistic portrayal of what may actually happen in some languages.

The Print statement will also be used in our pseudocode to indicate output to the screen, just as the Write statement does, including the ability to concatenate variables and text. However, until a  newline indicator is used, it is to be assumed that output from any subsequent Print statements will be on the same line. The newline indicator that we will use is  <NL> . 2

2 To create output in RAPTOR that does not automatically begin on a new line with each Output symbol, refer to the Running With RAPTOR section in  Chapter 5 . Recall that you must uncheck the End Current Line box at the bottom of the Enter Output Here dialog box.

For example, notice how the output displayed by the following two program segments differs:

Code

Code

Write "Hi"

Write "Ho"

Write "Done"

Print "Hi"

Print "Ho" <NL>

Print "Done"

Display

Display

Hi

Ho

Done

HiHo

Done

Example  6.9  utilizes the Print statement and the <NL> indicator.

Example 6.9 Using the Length_Of() Function for Formatting

In this example, we will practice using an If-Then statement nested in a loop to format screen display. Later in this chapter we will add to this program to create more interesting formatting. The pseudocode shown below allows the user to enter his or her name, and the name will be displayed with a line of symbols (chosen by the user) under the name. The number of symbols will match the number of characters in the name. To do this, we will use the Length_Of() function. The Print statement allows output within a loop to be displayed on a single line. The pseudocode for this program is as follows:

1 Declare Name As String

2 Declare Symbol As Character

3 Declare Number As Integer

4 Declare Choice As Character

5 Declare Count As Integer

6 Set Count = 0

7 Write "Enter your name: "

8 Input Name

9 Write "Choose one of the following symbols: "

10 Write " * or # "

11 Input Symbol

12 Write "Do you want a space between each symbol?"

13 Write "Enter 'Y' for yes, 'N' for no"

14 Input Choice

15 Set Number = Length_Of(Name)

16 Print Name <NL>

17 While Count <= Number

18 If Choice == "y" OR Choice == "Y"

19 Print Symbol + " "

20 Set Count = Count + 2

21 Else

22 Print Symbol

23 Set Count = Count + 1

24 End If

25 End While

26 Print <NL>

27 Write "How does that look?"

What Happened?

· Lines 1 through 6 declare and initialize the variables needed for the program.

· Lines 7–14 prompt for and accept initial values from the user.

· Line 15 extracts the number of characters in the user’s name through the Length_Of() function.

· Line 16 displays the user’s name on the screen. It uses the Print statement but ends with the <NL> indicator. This means that the next output statement will begin on the next line.

· Line 17 begins the While loop.

· The If statement on line 18 does two things. It checks the value of Choice to see if the user wants to put a space between each symbol, and it adds a little programming to make this program segment more “user-friendly.” By using a compound condition, with an OR operator, the program allows for a user to type in either an uppercase or a lowercase response. You may have noticed that sometimes, when you use any computer program, either upper or lower case responses are accepted but sometimes the case is significant. Good programmers try to think ahead of the users and account for many possible user responses when writing code.

· If the user has entered a "y" (or a "Y"), the program continues to line 19 where the chosen symbol is displayed with a space, and the counter is incremented on line 20.

· By using the Print statement on line 19 without the <NL> indicator at the end, the next time this line is executed the second output will be displayed on the same line.

· Let’s think about line 20 for a moment. We want our display to be the person’s name with a line of symbols underneath. If the user does not select a space between symbols, then the number of symbols will match the number of characters in the name. The loop has been written to execute until the value of Count matches the value of Number (the number of characters in the name). However, if the user wants a space between symbols and we simply increment Count by 1 on each pass, the line of symbols would extend twice as long as the name. If we increment Countby 2 in this case, instead of 1, the loop will now end when the number of characters in the symbol line (a symbol and a space for each iteration) matches the number of characters in the name.

· If the user has entered any character except y or Y, the Else option will be executed. In this case, a symbol with no space will be displayed (line 22) before the counter is incremented on line 23. The Print statement on line 22 without the <NL> indicator allows the next symbol (when this line is executed on the next iteration) to be displayed on the same line.

· Control returns to line 17 after either of the If-Then-Else options have been completed. The loop executes again and again until the counter is greater than Number and then it ends. In this way, the number of symbols displayed will match the number of characters in Name.

· Line 26 forces the next output to be on the following line. If we leave this line off, the statement "How does that look?" would be on the same line as the line of symbols.

Following is the code for this program in C++ along with the display, assuming the user has entered Joe for Name, # for Symbol, and has not chosen to put spaces between symbols. Notice that the new line indicator in C++ is endl.

int count = 0; int number = 0;

string name = " ";

char symbol = '#'; char choice;

cout << "Enter your name: ";

cin >> name;

number = name.length();

cout << "Choose a symbol: * or # ";

cin >> symbol;

cout << "Do you want a space between each symbol?";

cout << "Enter Y for yes, N for no.";

cin >> choice;

cout << name << endl;

while (count <= number)

{

if ((choice == 'Y') || (choice == 'y'))

{

cout << symbol << " ";

count = count + 2;

}

else

{

cout << symbol;

count = count + 1;

}

}

return 0;

Display:

Joe

###

Self Check for Section 6.2

For Self Check for  Section  6.7  and 6.8 refer to  Example  6.7   .

1. 6.7 Which of the following variables should be checked for validity? For each variable you select, identify what needs to be validated.

ItemCost, ItemTotal, Tax, Ship, Count, NumItems

2. 6.8 Walk through the pseudocode provided in  Example  6.7  and find out what would be displayed at the end if the customer purchased the following three items:

3. A widget for $55.98

4. A wonka for $23.89

A womble for $103.50

5. 6.9 Write a program segment that asks a user to enter the username he or she wants and checks the length of the entry. The username can be between 1-15 characters, inclusive. Since the space you have allowed for the username can only hold 15 characters, check to make sure the user’s entry is no longer than this.

6. 6.10 Create a program segment using Print statements, the <NL> indicator, and loops to display the following:

7.

8. & & & & & & & & & &

9. # # # # # # # # # #

10. & & & & & & & & & &

11. 6.11 The following pseudocode allows the user to enter five numbers and displays the absolute value of the inverse of each number. It is missing something. Find the missing condition and fix the pseudocode.

12. Declare Count As Integer

13. Declare Number As Float

14. Declare Inverse As Float

15. Set Count = 1

16. Do

17. Write "Enter a number: "

18. Input Number

19. If Number > 0

20. Set Inverse = 1/Number

21. Else

22. Set Inverse = (−1)/Number

23. End If

24. Write Inverse

25. Set Count = Count + 1

While Count <= 5

6.3 Random Numbers

Random numbers are numbers whose values form an unpredictable sequence. They have many interesting applications in programming. Although one of their major uses is to provide an element of chance in computer games, they also have other important functions, as in simulating situations or processes in business, mathematics, engineering, and other disciplines. In this section, we will discuss how to use random numbers in your programs.

The Random() Function

Most programming languages contain a function that is used to generate a sequence of random numbers, although the name of this function and the way it works varies from language to language. To illustrate the use of random numbers, we will define a function of the following form:  Random() . When the program encounters the expression Random(), which may appear anywhere that an integer constant is valid, it generates a random number from 0.0 to 1.0, including 0.0but not 1.0. This may, initially, not seem very helpful. After all, how many situations can you think of that can use a random number like 0.2506 or 0.0925? While randomly generated numbers like these may have some esoteric uses, it is far more common to require integer random numbers in a specific range. For example, in simulating the roll of a single die (one of a pair of dice), the possible outcomes are 1, 2, 3, 4, 5, and 6. Therefore, we normally manipulate the generated number to turn it into an integer in the range we require. This may take several steps.

For the purposes of illustration, the random numbers generated here as examples will have four decimal places (the actual number of decimal places generated depends on the computer system and the specific language’s compiler or interpreter). For example, Random() might generate 0.3792 or 0.0578. If we multiply the random number by 10, we will generate numbers between 0 and 9.9999, as shown in the following:

· If Random() = 0.3792, then Random() * 10 = 3.7920

· If Random() = 0.0578, then Random() * 10 = 0.5780

· If Random() = 0.1212, then Random() * 10 = 1.2120

· If Random() = 0.9999, then Random() * 10 = 9.9990

We have increased the range from 0.000 up to, but not including, 10. And we still do not have integer values. But we do have the Floor() function! If we take theFloor() of any random number, we will simply drop the decimal part, as you can see from the following:

· If Random() = 0.3792, then Floor(Random() * 10) = 3

· If Random() = 0.0578, then Floor(Random() * 10) = 0

· If Random() = 0.1212, then Floor(Random() * 10) = 1

· If Random() = 0.9999, then Floor(Random() * 10) = 9

We now have random numbers between 0 and 9. Finally, if we wish to generate a random number between 1 and 10, we can simply add 1 to the expression to get:

· If Random() = 0.3792, then (Floor(Random() * 10) + 1) = 4

· If Random() = 0.0578, then (Floor(Random() * 10) + 1) = 1

· If Random() = 0.1212, then (Floor(Random() * 10) + 1) = 2

· If Random() = 0.9999, then (Floor(Random() * 10) + 1) = 10

To use the random number generator in a program, you assign its value to an integer variable. To generate random numbers in any range desired, change the multiplier and/or the number added, as needed.  Example  6.10  demonstrates this.

Example 6.10 Generating Random Numbers with the Random() Function

If NewNumber is an integer variable, then:

· NewNumber = Floor(Random() * 10) + 1 will result in a random number between 1 and 10 (inclusive)

· NewNumber = Floor(Random() * 100) + 1 will result in a random number between 1 and 100 (inclusive)

· NewNumber = Floor(Random() * 10) + 4 will result in a random number between 4 and 13 (inclusive)

· NewNumber = Floor(Random() * 2) will result in either 0 or 1

· NewNumber = Floor(Random() * 2) + 1 will result in either 1 or 2

·  NewNumber = Floor(Random() * 6) + 7 will result in a random number between 7 and 12 (inclusive)

After examining these examples, we can conclude that, to generate a sequence of N random integers beginning with the integer M, use:

Floor(Random() * N) + M

Example 6.11 Flipping a Coin 3

3 To generate a random number in RAPTOR, use the RAPTOR’s random function. The function returns a random number in the same range as discussed here. To generate a random integer from A to B, assuming A and B are positive integers and A is less than B, use floor((random * B) + A). For example, you can simulate the roll of a die (a random number from 1 to 6) with floor((random * 6) + 1).

This simple program segment uses the Random() function to simulate a coin toss. If a 1 is generated, the program displays Heads and, if a 0 is generated, the program displays Tails. We put the coin toss in a While loop, which can be run as often as the user wants.

1 Declare Number As Integer

2 Declare Response As Character

3 Write "Do you want to flip a coin?"

4 Write "Enter 'y' for yes, 'n' for no: "

5 Input Response

6 While Response == "y"

7 Set Number = Floor(Random() * 2)

8 If Number = 1 Then

9 Write "Heads"

10 Else

11 Write "Tails"

12 End If

13 Write "Flip again? Enter 'y' for yes, 'n' for no: "

14 Input Response

15 End While

Line 7 uses the Random() function to generate either a 0 or 1. That value is then stored in the variable Number and is used to determine the result of the coin toss.

Example  6.12  provides a more advanced illustration of how random numbers can be used to make a probability prediction.

Example 6.12 Winning at Dice

Suppose a pair of dice is rolled and its sum is recorded. For example, if the first die comes up 3 and the second comes up 6, we record the value 9. Your friend suggests that now that you are such an expert with computers, you might be able to use a computer to predict a good strategy for playing a game that uses dice. She asks you to write a program to generate what outcomes are most likely. She wants to know if it is more likely that the sum of a roll of a pair of dice will be 5 or 8.

We can answer this question by simulating an experiment with a program that uses random numbers. For each roll of the dice, we need to generate two random numbers—one for each die—in the range from 1 to 6. Then we add these numbers and keep track of the number of times the sum is 5 or 8. If we roll the dice (generate a pair of random numbers) thousands of times, the sum (5 or 8) with the larger count is presumably the one that is more likely to occur. Here’s a program that carries out this plan.

1 Declare FiveCount As Integer

2 Declare EightCount As Integer

3 Declare K As Integer

4 Declare Die1 As Integer

5 Declare Die2 As Integer

6 Declare Sum As Integer

7 Set FiveCount = 0

8 Set EightCount = 0

9 For (K = 1; K <= 1000; K++)

10 Set Die1 = Floor(Random() * 6) + 1

11 Set Die2 = Floor(Random() * 6) + 1

12 Set Sum = Die1 + Die2

13 If Sum == 5 Then

14 Set FiveCount = FiveCount + 1

15 End If

16 If Sum == 8 Then

17 Set EightCount = EightCount + 1

18 End If

19 End For

20 Write "Number of times sum was 5: " + FiveCount

21 Write "Number of times sum was 8: " + EightCount

The best thing about this program, if it were actually coded and run, is that the computer would give us results in few seconds! It would take a person many hours to do this by hand. And, of course, if you think that 1,000 rolls of the dice is not enough to make an adequate prediction, just change the value of 1,000 to 10,000 or 2 million and you’ll still get results in seconds. You can try this yourself using RAPTOR.

What do you think? If we code and run this program segment, which sum do you think is more likely to occur? Can you justify your reasoning?

Consider the number of ways the sum of 5 can be obtained by rolling the dice and compare that with the number of ways the sum of 8 can be obtained by rolling the dice.

When two dice are rolled, the possible sums are 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, and 12. However, the possible combinations of two dice are as follows:

Possible ways to roll the 11 possible sums

Possible ways to roll a 5

Possible ways to roll an 8

1 + 1 = 2

2 + 1 = 3

3 + 1 = 4

4 + 1 = 5

5 + 1 = 6

6 + 1 = 7

(1,4)

(2,6)

1 + 2 = 3

2 + 2 = 4

3 + 2 = 5

4 + 2 = 6

5 + 2 = 7

6 + 2 = 8

(4,1)

(6,2)

1 + 3 = 4

2 + 3 = 5

3 + 3 = 6

4 + 3 = 7

5 + 3 = 8

6 + 3 = 9

(2,3)

(3,5)

1 + 4 = 5

2 + 4 = 6

3 + 4 = 7

4 + 4 = 8

5 + 4 = 9

6 + 4 = 10

(3,2)

(5,3)

1 + 5 = 6

2 + 5 = 7

3 + 5 = 8

4 + 5 = 9

5 + 5 = 10

6 + 5 = 11

(4,4)

1 + 6 = 7

2 + 6 = 8

3 + 6 = 9

4 + 6 = 10

5 + 6 = 11

6 + 6 = 12

There are 36 possible combinations and 11 possible sums. Since there are 4 ways to get a sum of 5 from 36 possible results, the probability of rolling a 5 is 4/36 (approximately 11.1%). Similarly, since there are five ways to get a sum of 8 from the 36 possible results, the probability of rolling an 8 is 5/36 (approximately 13.9%).

This means that, were you to roll two dice many, many times, over the long run, for every 100 times the dice are rolled and summed, there will be approximately 11 times that the sum will be 5 and approximately 14 times when the sum will be 8.

Earlier in this chapter, we created a simple guessing game in  Example  6.3 . Now, with the help of the Random() function, we can create a more interesting guessing game.  Example  6.13  illustrates how to do this.

Example 6.13 Another Guessing Game

This program allows the user (presumably a young child) to play a guessing game with the computer. The program generates a random integer (stored in a variable named Given) from 1 to 100, and the child has to guess this number.

1 Declare Given As Integer

2 Declare Guess As Integer

3 Set Given = (Floor(Random() * 100)) + 1

4 Write "I'm thinking of a whole number from 1 to 100."

5 Write "Can you guess what it is?"

6 Do

7 Write "Enter your guess: "

8 Input Guess

9 If Guess < Given Then

10 Write "You're too low."

11 End If

12 If Guess > Given Then

13 Write "You're too high."

14 End If

15 While Guess != Given

16 Write "Congratulations! You win!"

What Happened?

In this pseudocode, once the random integer is generated, the loop allows the user to repeatedly guess the value of the unknown number. To hasten the guessing process, the If-Then statements tell the user whether the guess is below or above the number sought. When the number guessed matches the number given, the loop is exited and the game is over.

Can you see a problem with the pseudocode provided in  Example  6.13 ? If, for example, the random number generated was 64 and the child playing the game guessed 87, the display would say that this guess is too high. A clever child might quickly figure out that his or her next guess should be less than 87. The next guess might be 18 and the computer would tell the child that this guess was too low. Our clever child would realize that the number then had to be between 19 and 86 and would continue to make guesses that zoom in on the correct number, using the messages "You're too high" and "You're too low" as hints. But what if the child continued to make guesses without regard to the messages? This program could go on indefinitely. This pseudocode should have some limitations. For example, the whole program might be contained in a loop that restricts the number of guesses or asks the player if he or she wants to end the guessing process and see the correct number displayed. We will return to this program in the Focus on Problem Solving section.

Not Really Random: The Pseudorandom Number

What does it actually mean to generate a random number? For a number (in a given set of numbers) to be selected truly at random, there must be an equal chance for any number to be selected.

However, no one can just tell a computer, “Pick any number between 0 and 1.” A computer must receive instructions from a program. A programmer must write a program to instruct the computer about how to select a number in a given range. Random numbers are often produced by means of a  mathematical algorithm—a formula (in a program) that instructs the computer how to pick some number in the range we specify. The algorithm might include instructions to multiply a number by something, divide by something else, raise the result to a power, and so forth. But the algorithm requires some beginning value to manipulate. This starting number is called the  seed value.

The number generated by the algorithm is used as the seed to generate the next random number. If the same seed is used each time the program calls for a random number, the numbers generated are not really random. So the numbers generated like this are not unpredictable, even though they are all equally likely to occur. Such numbers are called  pseudorandom but are generally just as useful as those that are truly random.

When a function that generates random numbers in this way is encountered in a program, some programming languages always use the same seed to generate the pseudorandom numbers unless specified otherwise. Therefore, if the starting value of the algorithm does not change, the same sequence of numbers will be produced each time the program is executed. This is useful for debugging purposes, but after a program is functioning correctly, you must force the computer to use a different seed on each run so that the random numbers produced will indeed be unpredictable. This is usually accomplished by placing a statement at the beginning of the program or program module that changes the seed from run to run. One way to make a pseudorandom number less predictable is to use a seed that is not predetermined. For example, you could use the number of milliseconds since the beginning of the current year as a seed. While this is not truly a random number, it will only occur once a year and therefore, is not likely to be repeated. This type of seed forces a random number generator to start with a different seed each time it is run because the time will be different in each run.

Self Check for Section 6.3

1. 6.12 Give the range of the random numbers generated by the following statements:

a. Set Num1 = Floor(Random() * 4)

b. Set Num2 = Floor(Random() * 2) + 3

c. Set Num3 = Floor(Random() * X) − 2, where X = 5

2. 6.13 Write a program that displays 100 random integers between 10 and 20 (inclusive).

3. 6.14 Write a program that uses random numbers to simulate rolling a single die and displays the results. Allow the user to input the number of rolls of the die.

4. 6.15 Rewrite the pseudocode provided in  Example  6.13  to use:

a. one If-Then-Else structure instead of two If-Then statements

b. one Select Case statement instead of two If-Then statements

5. 6.16 What is a pseudorandom number and how does it differ from a truly random number?

6.4 Nested Loops

Often, programs employ one loop that is contained entirely within another. In such a case, we say that they are  nested loops. The larger loop is called the  outer loop and the one lying within it is called the  inner loop. Students sometimes find it difficult to follow the logical sequence of steps that occurs when nested loops are implemented. Therefore, we will spend quite a bit of time developing short program segments with nested loops and will step through each line of each program carefully. Now, more than ever, it is important to walk through ( desk check) the pseudocode with paper and pencil, carefully writing down the values of each variable at each step.

Nested For Loops

In a nested loop program, the outer loop works as a regular loop. The inner loop is simply part of the loop body of the outer loop. The flowchart shown in  Figure  6.5  demonstrates the flow of a program with a nested loop where the inner loop completes three iterations and the outer loop completes two iterations. We will walk through the logic of this flowchart.

In  Figure  6.5 , the outer loop begins by testing the value of the integer variable, OutCount. The test condition says to repeat this loop, while OutCount is less than or equal to 2. When the loop begins, OutCount = 1 so the body of this loop is entered. The first thing that happens is that an integer variable, InCount, is initialized to 1.

Figure 6.5 Flowchart of nested For loops

Next, the inner loop is entered. The entire inner loop must be contained in the outer loop. In this case, the test condition specifies that the inner loop will continue until InCount is greater than 3. Therefore, the inner loop body is executed for three iterations. The body of this loop displays the value of OutCount on one line and the value of InCount on the next line.

On the first pass through the inner loop, OutCount = 1 and InCount = 1. That is what is displayed. On the second pass, OutCount is still 1 but InCount has beenincremented to 2. So a 1 is again displayed and, under it, a 2 is displayed. On the third pass, OutCount is still 1 and now InCount is 3. The fifth and sixth lines of the display are 1 and 3. Then, since InCount is incremented to 4, it fails the test condition and the inner loop is exited.

Next, a line is skipped and then OutCount is incremented to 2. Now we begin the outer loop a second time. Notice that the counter for inner loop, InCount, must be set equal to 1 again at this point. If this did not happen, the inner loop would never execute a second time because the value of InCount was 4 when the inner loop ended the first time.

The inner loop now goes through three more iterations, as before. This time it displays the new value of OutCount (2) each time around as well as the new values of InCount (1, 2, and 3). When InCount reaches 4, the inner loop is exited, a line is skipped, and OutCount is incremented to 3.

The program now ends since OutCount fails the test condition. The display, after the program is coded and run, will look as follows:

1

1

1

2

1

3

2

1

2

2

2

3

Examples  6.14  and  6.15  use For loops to further illustrate the order in which the loop iterations (the passes through the loops) take place when we nest one loop inside another. The flowchart for  Example  6.14  is shown in  Figure  6.6 .

Example 6.14 Using Nested For Loops to Display a Lot of Beans

Let’s say we want to write a program that will count twenty "bean"s and put them in four groups with five "bean"s in each group.

The inner loop counts five "bean"s. We know how to create this simple loop. We could repeat the loop four times to get the result we want, but that would be a long and boring process. Instead, we can put the little loop to display five "bean"s per group inside an outer loop, which simply says to repeat the inner loop four times.

The pseudocode for this program segment is as follows with a corresponding flowchart:

1 Declare OutCount As Integer

2 Declare InCount As Integer

3 For (OutCount = 1; OutCount <=4; OutCount++)

4 For (InCount = 1; InCount <=5; InCount++)

5 Write "bean"

6 End For(InCount)

7 Write " "

8 End For(OutCount)

Figure 6.6 Flowchart for Nested For Loops

What Happened?

· Line 3 begins the outer loop. We want this loop to go through four iterations because each iteration displays one group of five "bean"s. So line 3 checks to make sure that the counter for the outer loop (OutCount) is not greater than 4. If OutCount is greater than 4, the program jumps to line 8. Otherwise, it proceeds to line 4.

· Line 4 begins the inner loop. This loop displays one "bean" and increments InCount by 1 each time it runs through a pass. We want it to complete five iterations which will display five "bean"s. When InCount reaches past 5, the limit condition is not true, the inner loop ends for the first time, and the program proceeds to line 7.

· Line 5 simply displays the word "bean". The next "bean" will be displayed right under this "bean", and this will continue until the loop is exited.

· The Write " " statement on line 7 simply displays a blank line. If we leave this line out, all 20 "bean"s would be displayed without a break. After this,OutCount is incremented by 1, the value is checked to see if it is still less than or equal to 4, and, if it is, the inner loop begins again.

· Note that when the inner loop begins each time, a new outer loop iteration happens; InCount is reset to 1 so it can go through five passes again.

· Each time the inner loop runs, a list of five "bean"s is displayed. Each time the outer loop runs, the inner loop displays the list of five "bean"s and the display skips a line. So we get four groups of five "bean"s.

 Two Ways to Nest For Loops

If For loops have any statements in common, then one of them must be nested entirely within the other. They may not partially overlap! The inner loop must end before control passes again to the outer loop and their counter variables normally must be different. To illustrate, the following sets of pseudocode show two different valid ways in which three For loops may be nested.

Example A

Example B

For (I = . . .)

For (J = . . .)

Loop body

End For(J)

For (K = . . .)

Loop body

End For(K)

End For(I)

For (I =  . . . )

For (J =  . . . )

For (K =  . . . )

Loop body

End For(K)

End For(J)

End For(I)

In Example A, two completely separate loops (J and K) are nested inside the outer loop (I). In Example B, the K loop is nested completely inside the J loop, and the J loop is nested completely inside the I loop. Both ways are perfectly acceptable, but the results will often differ. The type of nesting that is chosen for any specific program will depend on the program’s requirements.

Nesting Other Kinds of Loops

Example  6.14  illustrates the nesting process with For loops. However, it is possible to nest one type of loop inside a different type of loop. The following examples demonstrate how to nest While, Repeat...Until, Do...While, and For loops.

In  Chapter  5 , we used a loop to calculate an exam average for one student in one class by inputting each exam grade. This works for one student, but you could use an outer loop to have the program accept information for all the students in a class.  Example  6.15  demonstrates how to use nested loops to allow the user to find exam averages for many students. The example nests a For loop inside a While loop. The flowchart tracing the flow of execution for this example is shown in  Figure  6.7 .

Example 6.15 Everyone’s Exam Averages

This program segment pseudocode allows a user to enter exam scores for as many students as the user wants using a While loop. In this example, it is assumed that each student has only three exams in the class, but the program can easily be altered to enter more or less exam scores by simply changing the limit condition in the nested For loop and the divisor on line 16. The pseudocode for this program segment is as follows:

1 Declare Count As Integer

2 Declare Name As String

3 Declare Score As Float

4 Declare ExamTotal As Float

5 Declare ExamAverage As Float

6 Set ExamTotal = 0.0

7 Set ExamAverage = 0.0

8 Write "Enter a student's name or enter * to quit: "

9 Input Name

10 While Name != "*"

11 For (Count = 1; Count < 4; Count++)

12 Write "Enter exam score number " + Count

13 Input Score

14 Set ExamTotal = ExamTotal + Score

15 End For

16 Set ExamAverage = ExamTotal/3

17 Write "Student: " + Name

18 Write "Exam average: " + ExamAverage

19 Write "Enter another student's name or '*' to quit:"

20 Input Name

21 Set ExamTotal = 0.0

22 End While

What Happened?

· The outer loop is a While loop and it begins on line 10, after the first name has been input. If the user has initially entered an asterisk (*), this loop will never be entered and nothing is displayed. Otherwise, control immediately goes to the inner loop, which begins on line 11.

· The inner loop is a For loop. Since for this example, we have assumed that each student has taken three exams, the counter is set to begin at 1 and to go through three iterations. For each iteration, one exam score (Score) is entered and a total is kept (ExamTotal).

· Line 12 uses the value of Count in the display. On the first pass through this loop, the value of Count is 1 so the prompt says "Enter exam score number 1". On the second pass, Count is 2 so the prompt says "Enter exam score number 2", and so on.

· Line 14 keeps a sum of these scores.

· When three scores have been entered, Count is incremented to 4, the test condition is no longer valid so the inner loop is exited. Control goes to the next line in the outer loop.

· Line 16 computes that student’s exam average, and lines 17 and 18 display the result.

· Lines 19 and 20 give the user the opportunity to enter another student’s scores or to end the program. Line 21 resets the ExamTotal to zero so the next student’s sum will begin with 0. Control then returns to the top of the outer While loop. If the name entered is not an asterisk, the inner loop runs again.

· This process continues until the exam scores have been entered, averages calculated, and results displayed for all the students.

Figure 6.7 Flowchart of nested While and For loops

Example  6.16  contains nested Repeat...Until and While loops. A flowchart tracing the flow of execution in this example is shown in  Figure  6.8 .

Example 6.16 Using Repeat...Until and While Nested Loops

This pseudocode makes use of a post-test Repeat...Until loop to allow the user to sum several sets of numbers in a single run. The outer loop allows the entire program to be executed again if the user desires. It also contains statements that initialize the sum to 0, input the first number, explain that 0 is the sentinel value, and then display the sum computed by the inner While loop.

1 Declare Sum As Float

2 Declare Number As Float

3 Declare Response As Character

4 Repeat

5 Set Sum = 0

6 Write "I can do addition for you!"

7 Write "Enter the first number you want to add: "

8 Write "Enter 0 when you're done."

9 Input Number

10 While Number != 0

11 Set Sum = Sum + Number

12 Write "Enter your next number or 0 if you are done: "

13 Input Number

14 End While

15 Write "The sum of your numbers is " + Sum

16 Write "Sum another list of numbers? (Y or N)"

17 Input Response

18 Until Response == "N"

Notice that with the exception of its last three statements, the body of the outer Repeat...Until loop contains the usual pseudocode for summing a set of numbers input by the user. The last statements in this loop ask the user if he or she would like to do another sum, input this response, and then use it in the test condition for the outer Repeat...Until loop.

Figure 6.8 Flowchart of nested Do...While (or Repeat...Until) and While loops

Example 6.17 Drawing Squares with Nested Loops

Example  6.9  demonstrates how to draw a line of symbols under a user’s name using a combination of a loop and an If-Then-Else structure. In this example, we will build on this concept and use nested While loops to draw a square on the screen. You can add other options to this program; some of these will be part of the Self Check questions and the Programming Challenges at the end of this chapter. The pseudocode for this program is as follows:

1 Declare Count1 As Integer

2 Declare Count2 As Integer

3 Declare Symbol As Character

4 Declare Side As Integer

5 Write "Choose a symbol (any character from the keyboard): "

6 Input Symbol

7 Write "Enter the length of a side of the square: "

8 Input Side

9 Set Count1 = 1

10 Set Count2 = 1

11 While Count1 <= Side

12 While Count2 <= Side

13 Print Symbol

14 Set Count2 = Count2 + 1

15 End While

16 Print <NL>

17 Set Count2 = 1

18 Set Count1 = Count1 + 1

19 End While

What Happened?

In this program segment, the user can choose any symbol from the keyboard, which is stored in the variable Symbol. The user also chooses the length of the sides of the square, which is stored in the integer variable, Side.

Since a square has the same length as width, the program needs to draw X number of symbols horizontally for X rows (if X represents the value of Side). The inner loop draws one row of symbols. The outer loop repeats the inner loop for the correct number of rows.

Notice that the Print statement on line 13, inside the inner loop, will allow symbols to be displayed all on one line. Line 16, however, simply says Print <NL>. This statement just instructs the output to begin on a new line. In a statement like this, there is no output to the screen.

A Mental Workout: Mind Games

By now you probably have realized that computers don’t process information like humans. People can understand concepts like “pick up some bread when you’re at the store” or “put that book down” or “make my coffee with a little cream and sugar.” Computers can’t process statements like that. Computers need exact, precise directions. In some ways, this makes it easier to write instructions because there can be no errors. A computer would never give you a cup of coffee that is too sweet or with too little cream. Unless you specify the exact amount of cream and sugar, you would get nothing. On the other hand, if you write a coffee preparation program correctly, you would always get a perfect cup of coffee. As you can see, there are pros and cons to this way of “thinking.” The downside is that it is often much more difficult for humans to create and follow such a program. The upside is that, when it works, it always works and always works correctly.

Examples  6.18 6.20  use nested loops. A computer finds these instructions easy to process, but they can be challenging for a beginning programmer. The following examples will help you practice and understand loops, nested loops, and the pure logical thinking needed to write programs that do what you want them to do.

Example 6.18 Workout Number 1: Beginner

This pseudocode makes use of nested While loops.

1 Declare X As Integer

2 Declare Y As Integer

3 Declare Z As Integer

4 Set X = 1

5 While X < 4

6 Write "Pass Number " + X

7 Set Y = 1

8 While Y < 10

9 Set Z = X + Y

10 Write X + " + " + Y + " = " + Z

11 Set Y = Y + 3

12 End While(Y)

13 Set X = X + 1

14 End While(X)

What Happened?

The display, after this pseudocode is coded and run will look like this:

Pass Number 1

1 + 1 = 2

1 + 4 = 5

1 + 7 = 8

Pass Number 2

2 + 1 = 3

2 + 4 = 6

2 + 7 = 9

Pass Number 3

3 + 1 = 4

3 + 4 = 7

3 + 7 = 10

Now we’ll walk through the pseudocode and see exactly how this program works. As you begin to write programs in a programming language, you will need to walk through your code with a pencil and paper to see exactly what is happening. The best way to do this is to keep track of the value of each variable at every step of the program. This program has three variables so we will identify the value of each variable as the code is executed, line by line.

Outer Loop, Pass 1: X = 1 at start

Display: Pass Number 1

Inner Loop, Pass 1: Y = 1 at start

X = 1 , Y = 1, Z = 2

Display: 1 + 1 = 2

Y = Y + 3 so Y = 4

Inner Loop, Pass 2: Y = 4 at start

X = 1, Y = 4, Z = 5

Display: 1 + 4 = 5

Y = Y + 3 so Y = 7

Inner Loop, Pass 3: Y = 7 at start

X = 1, Y = 7, Z = 8

Display: 1 + 7 = 8

Y = Y + 3 so Y = 10

Inner Loop ends and X is incremented to 2

Outer Loop, Pass 2: X = 2 at start

Display: Pass Number 2

Inner Loop, Pass 1: Y = 1 at start

X = 2 , Y = 1, Z = 3

Display: 2 + 1 = 3

Y = Y + 3 so Y = 4

Inner Loop, Pass 2: Y = 4 at start

X = 2, Y = 4, Z = 6

Display: 2 + 4 = 6

Y = Y + 3 so Y = 7

Inner Loop, Pass 3: Y = 7 at start

X = 2, Y = 7, Z = 9

Display: 2 + 7 = 9

Y = Y + 3 so Y = 10

Inner Loop ends and X is incremented to 3

Outer Loop, Pass 3: X = 3 at start

Display: Pass Number 3

Inner Loop, Pass 1: Y = 1 at start

X = 3 , Y = 1, Z = 4

Display: 3 + 1 = 4

Y = Y + 3 so Y = 4

Inner Loop, Pass 2: Y = 4 at start

X = 3, Y = 4, Z = 7

Display: 3 + 4 = 7

Y = Y + 3 so Y = 7

Inner Loop, Pass 3: Y = 7 at start

X = 3, Y = 7, Z = 10

Display: 3 + 7 = 10

Y = Y + 3 so Y = 10

Inner Loop ends and X is incremented to 4

Now X fails the Outer Loop test condition so the program segment ends.

Example  6.19  demonstrates a harder example of the use of nested loops.

Example 6.19 Workout Number 2: Intermediate

In this pseudocode, a pre-test While loop is nested within a post-test Do...While loop.

To save space, we will assume that the following five variables have been declared as Integer type: X, Y, Z, Count1, and Count2. The pseudocode begins immediately following those declarations.

1 Set Y = 3

2 Set Count1 = 1

3 Do

4 Set X = Count1 + 1

5 Set Count2 = 1

6 Write "Pass Number " + Count1

7 While Count2 <= Y

8 Set Z = Y * X

9 Write "X = " + X + ", Y = " + Y + ", Z = " + Z

10 Set X = X + 1

11 Set Count2 = Count2 + 1

12 End While

13 Set Count1 = Count1 + 1

14 While Count1 < Y

What Happened?

The display, after this pseudocode is coded and run will look like this:

Pass Number 1

X = 2, Y = 3, Z = 6

X = 3, Y = 3, Z = 9

X = 4, Y = 3, Z = 12

Pass Number 2

X = 3, Y = 3, Z = 9

X = 4, Y = 3, Z = 12

X = 5, Y = 3, Z = 15

Now we’ll walk through the pseudocode and see exactly how this program works. Try doing it yourself with a paper and pencil and see if you get the same results as those shown. If not, check the explanation, shown below.

· Line 1 sets the variable Y equal to 3. Throughout the program, Y remains at this constant value.

· Line 2 initializes the counter for the outer loop, Count1, to 1. Note that the counter for the outer loop does not need to be reset during the program because once the outer loop ends, the program segment is complete. This is not the case for an inner loop, as we shall see.

· The outer Do...While loop begins on line 3. The loop will happen at least once because the test condition is not reached until the first iteration is complete. However, if we look down at line 14 we see that the test condition for this loop is While Count1 < Y. Y starts at 3 and its value does not change throughout the program so we see that the outer loop will complete only two iterations—when Count1 = 1 and when Count1 = 2.

· Line 4 sets a value of X. On the first pass, X will begin at 2 (Count1 + 1), on the second pass, X will begin at 3, and on the third pass, X will begin at 4.

· Line 5 initializes the counter for the inner While loop. This step is important. The inner loop ends when the counter has reached a certain value. If the counter were not reinitialized in the outer loop, the inner loop would never execute more than once.

· Line 6 displays the heading of the first or second pass, depending on the value of Count1.

· Line 7 begins the inner loop. The test condition for this loop is Count2 <= Y. Since Y remains at 3 throughout the program, we see that the inner loop will run for three iterations: while Count2 is 1, 2, and 3.

· The inner loop body (lines 8–11) assigns a value to Z, outputs the values of X, Y, and Z, increments the inner counter, Count2, and increments X. Here is what happens:

· On the first pass through the inner loop, while we are still in the first pass of the outer loop, Z is set to the value of Y * X which is 3 * 2.

· Line 9 displays "X = 2, Y = 3, Z = 6".

· Line 10 increments X, so X now equals 3.

· Count2 is then incremented to 2, the test condition is still valid, and the inner loop is executed again. This time Z = 3 * 3 so the values displayed are"X = 3, Y = 3, Z = 9". X is incremented again on line 10 to 4.

· Count2 is incremented to 3. Another pass through the inner loop is made. This time Z = 3 * 4 and the values displayed are "X = 4, Y = 3, Z = 12".

· Count2 is incremented to 4 and fails the test condition. The inner loop is exited and control goes to the outer loop on line 13.

· Count1 now is incremented to 2 so it is still less than Y and the outer loop makes another pass.

· Line 4 resets the value of X. This time X will have the value of 3 when we begin the inner loop.

· Line 5 resets the value of Count2 to 1 so the inner loop will run again.

· Line 6 displays the new header: "Pass Number 2".

· On this second pass, X begins with the value of 3. Therefore, the display (line 9) on the first pass will be "X = 3, Y = 3, Z = 9". Then X is incremented to4 on line 10.

· A second pass is made through the inner loop when Count2 is incremented to 2. The display now will be "X = 4, Y = 3, Z = 12". X is incremented to 5.

· A third pass is made through the inner loop when Count2 is incremented to 3. The display is "X = 5, Y = 3, Z = 15".

· When Count2 is incremented to 4, the inner loop is exited.

· Count1 is then incremented to 3 and also fails the outer loop test so the outer loop is exited and the program ends.

Let’s try one more.  Example  6.20  will include two While loops and an If-Then-Else statement. The math is simple; the logic is a lot harder. Before you look at the line-by-line explanation, walk through the pseudocode with a pencil and paper. Keep track of the value of each variable at each step. Also, write down the display as you walk through the code to see if your display matches the one shown.

Example 6.20 Workout Number 3: Expert

This pseudocode makes use of nested While loops and If-Then statements. Three Integer variables have been declared: A, B, and C.

1 Set A = 1

2 Write "Cheers!"

3 While A < 3

4 Set C = A

5 Write A

6 Set B = 1

7 While B < 4

8 Set C = C + A

9 Write C

10 If (A == 1 AND C >= 4) Then

11 Write "Let's do this some more!"

12 Else

13 If (A == 2 AND C >= 8) Then

14 Write "Who do we appreciate?"

15 End If

16 End If

17 Set B = B + 1

18 End While(B)

19 Set A = A + 1

20 End While(A)

What Happened?

The display, after this pseudocode is coded and run will look like this:

Cheers!

1

2

3

4

Let's do this some more!

2

4

6

8

Who do we appreciate?

Now we’ll walk through the pseudocode and see exactly what happens.

· Line 1 initializes the variable A.

· Line 2 simply displays the heading: "Cheers!".

· The outer loop begins on line 3. The variable A is tested to see if it is less than 3. Since it starts at 1 and is incremented by 1 at the end of each loop, there will be two passes through this outer loop—while A = 1 and A = 2.

· Line 4 sets the variable C equal to the value of A, and line 5 displays the value of A. At this point A = 1 and C = 1. The screen so far displays "Cheers!"on one line and "1" on the next line.

· Line 6 sets the initial value of B to 1. Notice that it is set before entering the inner loop so it is set to 1 for each iteration of the outer loop.

· Line 7 begins the inner While loop. Since the test condition says the loop will continue while B is less than 4, we know the inner loop will continue for three iterations.

· Line 8 sets C equal to its previous value plus the value of A. Now C equals 2. A "2" is displayed on the screen (line 9) under the "1".

· Line 10 is the first part of the If-Then-Else statement. It tests to see if A = 1 AND if C has reached 4. On the first pass, while the first condition is true, the second is not. As we know, the logical operator AND only returns a value of true if both conditions are true so line 11 is skipped.

· Line 12 begins the Else clause. Line 13 tests to see if A = 2 AND if C has reached the value of 8. Since neither condition is true, line 14 is skipped.

· B is incremented to 2 on line 17 and control passes back to line 8 where C is set to a new value: C now equals 2 + 1 or 3. The "3" is displayed under the "2".

· The If-Then-Else statements are tested again on lines 10 and 13 but, since the conditions fail these tests, lines 11 and 14 are skipped again.

· B is incremented to 3 and control passes back to line 8. C is now set equal to 4. A "4" is displayed under the "3".

· Line 10 once again tests the values of A and C. At this point A does equal 1 AND C equals 4 so line 11 is executed. "Let's do this some more!" is now displayed under the "4".

· The Else clause on lines 12–14 is skipped since the If clause was true.

· B is incremented to 4 so the inner loop ends.

· Control returns to line 3 and the outer loop begins again. Take note of the values of all the variables at this point: A = 2, B = 5, and C = 4.

· However, on line 4, C is reset to 2.

· Line 5 displays a "2" under the statement "Let's do this some more!"

· Now the inner loop begins again, on line 7 but first B is reset to 1 on line 6.

· The inner loop repeats, as before, except this time the first value of C (line 8) is  4 since C = C + A means C = 2 + 2. A "4" is displayed under the "2"(line 9).

· On this and the next two passes through the inner loop, the If clause on line 10 will never be true since now A = 2.

· On the second pass through the inner loop (B = 2), C will become 6 (line 8) and a "6" will be displayed.

· On the third pass through this loop (B = 3), C will be 8 and an "8" will be displayed.

· At this point, A = 2, B = 3, and C = 8. When control reaches line 13, both conditions in the Else clause are true since A does equal 2 and C is equal to8. Therefore, the statement on line 14 is executed and "Who do we appreciate?" is displayed under the "8".

· Now B is incremented to 4 (line 17) and the inner loop ends.

· Finally, A is incremented to 3 on line 19 and the outer loop ends.

· Note that, when this program ends, the final values of the variables are A = 3, B = 4, and C = 8.

Once you have walked through this program segment with a paper and pencil and you are sure you understand what happens, you are ready to tackle the Self Check questions for this section.

Self Check for Section 6.4

1. 6.17 What is the output of the code corresponding to the pseudocode shown?

2. Declare I, J As Integer

3. For (I = 2; I <= 4; I++)

4. For (J = 2; J <= 3; J++)

5. Write I + " " + J

6. End For(J)

End For(I)

7. 6.18 What is the output of the code corresponding to the pseudocode shown?

8. Declare I, J, K As Integer

9. For (I = 1; I <= 5; I+3)

10. Set K = (2 * I) − 1

11. Write K

12. For (J = I; J <= (I+1); J++)

13. Write K

14. End For(J)

End For(I)

15. 6.19 Draw a flowchart corresponding to the pseudocode of Self Check for Question 6.18.

16. 6.20 Refer to  Example  6.17  in this section and add pseudocode to validate the following input: Side

17. 6.21 Refer to  Example  6.17  in this section and change the pseudocode to allow the user to draw either a square or a rectangle.

18. 6.22 Write pseudocode containing two nested Repeat...Until loops that input and validate a number, MyNumber, to be greater than 0 and less than 10.

19. 6.23 How would you change the pseudocode provided in  Example  6.19  so that the outer loop would complete four iterations?

20. 6.24 How would the display provided in  Example  6.19  change if line 8 said Set Z = Y + X?

6.5 Focus on Problem Solving: A Guessing Game

In this chapter ( Example  6.13 ), we created a very simple guessing game using a loop, two selection structures, and random numbers. The Project Manager at a small educational software company has seen this program and decided it would make a good game for young children. The game can help young children learn numbers, understand the concepts of “higher” and “lower,” and help them begin to take a logical approach to problem solving. Since we have already written the skeleton of the game in  Example  6.13 , we are happy to tackle this project.

The program as written so far is a good start. We repeat the pseudocode here, for convenience.

1 Declare Given As Integer

2 Declare Guess As Integer

3 Set Given = Floor(Random() * 100) + 1

4 Write "I'm thinking of a whole number from 1 to 100."

5 Write "Can you guess what it is?"

6 Do

7 Write "Enter your guess: "

8 Input Guess

9 If Guess < Given Then

10 Write "You're too low."

11 End If

12 If Guess > Given Then

13 Write "You're too high."

14 End If

15 While Guess != Given

16 Write "Congratulations! You win!"

Problem Statement

But a real game programmer could not use the program as is. In this section, we will elaborate on this program to add features that make the game more realistic. While we will still have a long way to go before this simple program could be marketed, you will get a feel for the process involved in developing a marketable program. We will add the following features:

· The program only runs once so we must add code to allow the game to be played as often as desired.

· The program requires input, which must be validated.

· The program needs to end after a specific number of guesses.

· We will add features to allow the user to control how the game works as follows:

· The program uses a random number between 1 and 100. We will change this to allow the player to control the range of numbers.

· We will allow the player to decide how many guesses can be made before the program ends.

Problem Analysis

For this problem, we do not have to work backward from a desired output to figure out the input needed. We are revising a skeleton program by adding modules and code to give us the features we want. This is not unusual for a programmer in the real world. Programmers rarely write code from scratch. Much programming work consists of debugging, re-using, or enhancing other people’s code.

First, we need to add a Welcome module to explain the game. Then, we need to add a Setup module to define the options available. These options are as follows:

· Should the range of numbers be the default value of 1–100 or selected by a player?

· Should the number of guesses be a default value of 20 or selected by a player?

We need to add validation wherever necessary and, finally, we need to put the actual game inside a Game module and add a loop to allow the player to decide whether to play again or not.

The core of this program is the code that allows a player to guess a secret number by zeroing in on it from clues that indicate if the guess is too high or too low. Using a modular approach, we will develop the complete program with the following modules:

1. Main module, which calls the submodules into action

2. Welcome_Message module, which displays a welcome message

3. Setup module, which allows the user to personalize the game by selecting the range of numbers to be used and the number of guesses to be allowed

4. Game module, which is the actual game and will give the player an option to play again

The hierarchy chart shown in  Figure  6.9  shows the division of programming tasks for this program.

Figure 6.9 Hierarchy chart for the guessing game problem

Program Design

To design this program using a modular approach, we will describe the major tasks of each module. First, we give a rough outline of the program, then we refine it as necessary.

Main Module

The Main module only needs to call its immediate submodules; they will perform all the necessary program tasks. In the Main module, we also declare all the variables that will be used by more than one submodule. Later in this book, when we discuss functions and subprogams ( Chapter  9 ), we will learn how to declare variables within subprogams and pass their values from one subprogam to another. This is a more appropriate and realistic way to write code, but, for now, we will simply declare our variables once, in the Main module and assume that they are, therefore, available to all the subprogams. The resulting pseudocode is as follows:

Begin Program

Declare Given As Integer

Declare HighRange As Integer

Declare LowRange As Integer

Declare NumGuess As Integer

Declare Guess As Integer

Declare Response As Character

Call Welcome_Message module

Call Setup module

End Program

Welcome_Message Module

This module displays general information and briefly describes the program. It will consist only of Write statements, as follows:

Begin Welcome Message

Write "Guess My Secret Number!"

Write "This game allows you to guess a secret number by"

Write "using information provided for you with each guess."

Write "You only get a limited number of guesses,"

Write "so think carefully about each guess."

End Welcome Message

Setup Module

This module will ask the user to personalize the program parameters. It will receive information from the user about how to set up one game and then will call theGame module to begin playing. The tasks are as follows:

· Set the default values for the Integer variables to be used: the secret number (Given), the range of numbers (LowRange and HighRange), and the number of guesses (NumGuess), as well as a Character variable (Response) for the player’s responses to questions.

· Ask the user if the range of numbers to be used when generating the secret number should be between 1 and 100 (the default) or changed to something else. If the user opts to select a different range, the user’s input must be validated to ensure that the range consists only of whole numbers and that the high end of the range is greater than the low end. This requires three validation code segments. First, the value of LowRange (the lower limit of the range) must be checked to see if it is an integer. Then, the value of HighRange (the upper value of the range) must also be checked to see if it is an integer. Finally, the HighRange value must be validated to ensure that it is greater than the lower limit value. We will use two If-Then statements to accomplish this inside a loop, which checks both items.

· Ask the user if the number of guesses allowed (NumGuess) should be left at 20 (the default) or set to another value. Once again, if the user opts to change the number of guesses allowed, we must validate the input to ensure that a valid integer value has been entered since the number of guesses must be a whole number greater than 0.

· Pick a value for the secret number from a computer-generated random number in the range specified.

· Call the Game module to begin play.

The second-to-last item in this list requires a little extra attention. In  Example  6.13 , the secret number was simply set equal to a random number from 1 to 100. This was done using the Random() function. However, in the expanded program, we do not know what the range for selecting the secret number will be. If a player picks a range, the lower limit and upper limit are the values that are assigned to the variables LowRange and HighRange.

Now, we must find a way to use the Random() function to select a number in any given range. We know that the Random() function produces a number from 0 up to but not including 1. Let’s take one example and work through it to help us arrive at a general formula to get a random number in the desired range. Let’s assume that the player chooses a range from 4 to 12 for the secret number. Therefore, LowRange = 4 and HighRange = 12. We want a random number generated from the following choices: 4, 5, 6, 7, 8, 9, 10, 11, and 12. This is a total of nine numbers.

HighRange − LowRange in this case equals 8 but (HighRange − LowRange + 1) = 9. We know that Floor(Random() * 9) will result in a number between 0 and8, a total of nine integers. This formula works for any values of HighRange and LowRange; the difference between the two values, plus 1, gives us the number of choices we want.

While Random() * (HighRange − LowRange + 1) will generate a random number from 0 through 8, we need to shift the starting value so that it is 4. If we shift the number generated by 4 we get:

Floor(Random() * (HighRange − LowRange + 1)) + 4

This will generate the numbers 4, 5, 6, 7, 8, 9, 10, 11, or 12.

Of course, this will not work in the general case. We need to find a way to write the shift in general terms. If we add the value of LowRange to the generated random number, we can shift the numbers up to the value of LowRange.

The final formula for generating a random number between any two integer values and assigning that value to a variable named Given is, therefore:

Given = Floor(Random() * (HighRange − LowRange + 1) + LowRange

If you are not convinced, check the values that will be generated for several other values of HighRange and LowRange. For example, if HighRange = 35 andLowRange = 22, the secret number will be as follows:

Given        = Floor(Random() * (HighRange − LowRange + 1)) + LowRange

= Floor(Random() * (35 − 22 + 1)) + 22

= Floor(Random() * 14) + 22

= 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, or 35

Try some other values to convince yourself that this works.

Now we can write the pseudocode for this module. Since this module is rather long and accomplishes several distinct tasks, comments have been added to the pseudocode to help distinguish what is happening at various stages of this module. The pseudocode is as follows:

Begin Setup

Set HighRange = 100 // default value for upper limit

Set LowRange = 1 // default value for lower limit

Set NumGuess = 20 // default value for number of guesses

Set Response = ' '

Set Given = 0

/* Comment: The following pseudocode allows the user to select a range of numbers to be used for the secret number. The default values (HighRange = 100 and LowRange = 1) will not be changed if the user does not type 'y' when asked for a Response. */

Write "A secret number will be generated between 1 and 100."

Write "You can change these values to any values "

Write "that you want (whole numbers only)."

Write "Do you want to select your own range?"

Write "Type 'y' for yes or 'n' for no: "

Input Response

If Response == 'y' Then

Write "Enter the low value of your desired range: "

Input LowRange

While Int(LowRange) != LowRange

Write "You must enter a whole number. Try again: "

Input LowRange

End While

Write "Enter the high value of your desired range: "

Input HighRange

While (Int(HighRange) != HighRange) OR (HighRange <= LowRange)

If Int(HighRange) != HighRange Then

Write "You must enter a whole number. Try again: "

Input HighRange

End If

If HighRange <= LowRange Then

Write "The upper value must be greater than "

Write "the lower value. Try again: "

Input HighRange

End If

End While

End If

/* Comment: The following pseudocode allows the user to select how many guesses will be allowed for each run of the game. The default value (NumGuess = 20) will not be changed if the user does not type 'y' when asked for a Response. */

Write "The game normally allows a player 20 guesses."

Write "Do you want to change the number of guesses allowed?"

Write "Type 'y' for yes or 'n' for no."

Input Response

If Response == 'y' Then

Write "Enter the number of guesses you want to allow: "

Input NumGuess

While (Int(NumGuess) != NumGuess) OR (NumGuess < 1)

Write "You must enter a whole number greater than 0."

Write "Try again: "

Input NumGuess

End While

End If

/* Comment: The following pseudocode generates a random number in the range specified. */

Set Given = Floor(Random() * (HighRange − LowRange + 1)) + LowRange

Call Game Module

End Setup

Game Module

This module is the heart of the program. It uses the values of variables sent over from the Setup module. Later in this text we will learn how programming languages pass variables from one module to another and back again, but for now we will just accept that the values of Given, HighRange, LowRange, andNumGuess are passed from the Setup module into the Game module. Therefore, whatever values these variables have when the Setup module is finished will be the values they have when the Game module begins. The pseudocode for the Game module is as follows:

Begin Game

Declare Count As Integer

Set Count = 1

Write "I'm thinking of a whole number "

Write "between " + LowRange + " and " + HighRange

Write "Can you guess the number?"

Write "You have " + NumGuess + " chances to guess."

Input Guess

If Guess == Given Then

Write "Wow! You won on the first try!"

Else

While (Count <= NumGuess OR Guess != Given)

While (Int(Guess) != Guess)

Write "You must guess a whole number."

Write "Guess again: "

Input Guess

End While

If Guess < Given Then

Write "Your guess is too low. Guess again:"

Input Guess

Else

If Guess > Given Then

Write "Your guess is too high. Guess again:"

Input Guess

Else

Write "Congratulations! You win!"

End If

End If

Set Count = Count + 1

End While

End If

/* Comment: Next, a suitable message is displayed if the player has used up all the allowed guesses and has not correctly guessed the secret number. Then, in either case (the player won or lost), an option to play again is given.*/

If (Count > NumGuess AND Guess != Given) Then

Write "Sorry. You have used up all your guesses."

End If

Write "Do you want to play again?"

Write "Type 'y' for yes, 'n' for no: "

Input Response

If Response != 'y' Then

Write "Goodbye"

Else

Call Setup

End If

End Game

Program Code

The program code is now written using the design as a guide. At this stage, header comments and, where needed, more step comments are inserted into each module, providing internal documentation for the program.

This type of program—a computer game—would probably be used in a graphical environment so artists and graphic designers would be brought in to develop a graphical interface.

Program Test

The program test phase of developing this program is extremely important. As always, we need to test the program with many different sets of data. We need to be sure that we test each set of data with each possible option. For example, we need to test what happens when a player guesses correctly on a first guess when the range is set to the default, when the range is set by the player, using several possible ranges, where the range is set by the player and the number of guesses allowed is the default, as well as in each of these cases when the number of guesses is set by the player. In a program such as this, with many options that are set by the user, a bug may exist in one combination of events that may not show up in most or all other combinations. The testing should be done in a systematic, planned manner. You, as the programmer at this level, should use desk-checking to walk through the program pseudocode with all the possible data sets, as follows:

· In this testing phase, a programmer would add temporary code so that, when the secret number is assigned to Given, that value will be displayed. This is so that the programmer can test the results of the game using both correct and incorrect data. This code would, of course, be deleted from the final product.

· Tests should be made using the default values as follows:

· Check to see what happens in the Setup module when the user inputs ‘n’ or any character other than 'y' for responses to questions about the range and the number of guesses.

· Check the Game module, inputting values above and below the secret number as well as the actual correct secret number.

· Check what happens when the first guess is correct.

· Check what happens when all twenty guesses are incorrect.

· Tests should be made using values other than the defaults.

· Check what happens when appropriate and inappropriate values are entered for high and low values of the range. These tests should include both positive and negative integers, 0, and noninteger values.

· Check what happens when appropriate and inappropriate values are entered for the number of guesses, as for the range.

· Check the Game module as listed above but in each of the following cases:

· The user changes the range but does not change the default value for the number of guesses.

· The user changes the number of guesses but does not change the default values for the range.

· The user changes all default values.

Self Check for Section 6.5

For all of these Self Check questions refer to the Guessing Game problem described in this section.

1. 6.25 If HighRange = 13 and LowRange = 10, what possible numbers will be generated by the following formula?

Given = Floor(Random() * (HighRange − LowRange + 1)) + LowRange

2. 6.26 If HighRange = 7 and LowRange = 0, what possible numbers will be generated by the following formula?

Given = Floor(Random() * (HighRange − LowRange + 1)) + LowRange

3. 6.27 What should the values of HighRange and LowRange be, in the formula in the Self Check Question 6.25, to produce the following possible numbers: 40,41, 42, 43, 44, 45

4. 6.28 How could you change the formula in the Self Check Question 6.26 so that the range of numbers starts at 5?

5. 6.29 Write the pseudocode in the Game module to output the results of testing a single guess (too high, too low, or correct) using a Select Case statement instead of an If-Then-Else structure.

6. 6.30 Add pseudocode to the segment in the Setup module that asks the player to input a Response to the question "Do you want to change the number of guesses allowed?" that outputs a suitable message if the player does not type 'y'. Your pseudocode should check to make sure that the player did not type an incorrect character by mistake. In other words, validate the input to make sure that the player really meant to answer “no.”

Week 3 assignment.docx

Select two tasks a program could perform that would be useful to a small business.

Each task must include the following:

· A conditional step

· Some form of iteration

Example tasks include the following:

· Entering a number of items and calculating sales tax on a sale; include a step offering a warranty for each item

· Converting from Fahrenheit to Celsius or the reverse over temperatures for several days

· Figuring out a total bulk sale price based on price per unit and number of units

These items may build on the tasks used in your Week Two assignment or may be unique.

Create a 1/2-page Memo using the Memo Template for each of the tasks. Each document should include:

· A brief description of the task

· The pseudocode associated with the task. Base the pseudocode on the examples provided in Chs. 4, 5, and 6 of Prelude to Programming.

Create Visual Logic® files to execute each of the tasks.

Save all files in a single folder structure you zip into a single file to submit.

Submit the zip file containing all files using the Assignments Files tab.