Programming Logic and Design 2
Programming Logic and Design 2
Chapter 5
Exercises
Answer:
a. 5, 22, 5
b. 4, 6, 7
c. 5, 6
d. Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
e. Hello
Hello
Hello
f. Adios
Adios
Adios
Adios
Adios
Adios
Adios
Adios
2. Design the logic for a program that outputs every number from 1 through 10.
Answer:
A sample solution follows
Flowchart:
Programming Logic and Design, 6e Solutions 5-2
Pseudocode:
start
Declarations
num number
housekeeping()
number = 1
while number <= 10
detailLoop()
endwhile
finishUp()
stop
housekeeping()
number = 1
return
detailLoop()
output number
number = number + 1
return
finishUp()
output “End of program”
return
Programming Logic and Design, 6e Solutions 5-3
3. Design the logic for a program that outputs every number from 1 through 10
along with its square and cube.
Answer:
A sample solution follows
Flowchart:
Pseudocode:
start
Declarations
num number
num square
num cube
housekeeping()
while number <= 10
detailLoop()
endwhile
finishUp()
stop
Programming Logic and Design, 6e Solutions 5-4
housekeeping()
number = 1
return
detailLoop()
square = number * number
cube = square * number
output number, square, cube
number = number + 1
return
finishUp()
output “End of program”
return
4.Design the logic for a program that outputs every even number from 2 through 30.
Answer:
A sample solution follows
Flowchart:
Programming Logic and Design, 6e Solutions 5-5
Pseudocode:
start
Declarations
num number
housekeeping()
while number <= 30
detailLoop()
endwhile
finishUp()
stop
housekeeping()
number = 2
return
detailLoop()
output number
number = number + 2
return
finishUp()
output “End of program”
Programming Logic and Design, 6e Solutions 5-6
return
5. Design the logic for a program that outputs numbers in reverse order from 10
down to 1.
Answer:
A sample solution follows
Flowchart:
Pseudocode:
start
Declarations
num number
housekeeping()
while number >= 1
detailLoop()
endwhile
Programming Logic and Design, 6e Solutions 5-7
finishUp()
stop
housekeeping()
number = 10
return
detailLoop()
output number
number = number - 1
return
finishUp()
output “End of program”
return
Answer:
A sample solution follows
Flowchart:
Programming Logic and Design, 6e Solutions 5-8
Pseudocode:
start
Declarations
num accountNum
num balanceDue
num month
num paymentAmt
string custName
num PAY_RATE = 0.10
string PROMPT1 = “Enter an account number”
string PROMPT2 = “Enter the customer name and balance due”
housekeeping()
detail()
finishUp()
stop
housekeeping()
output PROMPT1
Programming Logic and Design, 6e Solutions 5-9
input accountNum
return
detail()
output PROMPT2
input custName, balanceDue
output accountNum, custName
month = 1
paymentAmt = balanceDue * PAY_RATE
while month <= 10
balanceDue = balanceDue – paymentAmt
output month, balanceDue
month = month + 1
endwhile
output PROMPT1
input accountNum
return
finishUp()
output “End of program”
return
Answer:
A sample solution follows
Flowchart:
Programming Logic and Design, 6e Solutions 5-10
Pseudocode:
start
Declarations
num accountNum
num balanceDue
num month
num paymentAmt
string custName
num PAY_RATE = 0.10
string PROMPT1 = “Enter an account number or 999 to exit”
string PROMPT2 = “Enter the customer name and balance due”
housekeeping()
while accountNum not equal to 999
detailLoop()
endwhile
finishUp()
stop
Programming Logic and Design, 6e Solutions 5-11
housekeeping()
output PROMPT1
input accountNum
return
detailLoop()
output PROMPT2
input custName, balanceDue
output accountNum, custName
month = 1
paymentAmt = balanceDue * PAY_RATE
while month <= 10
balanceDue = balanceDue – paymentAmt
output month, balanceDue
month = month + 1
endwhile
output PROMPT1
input accountNum
return
finishUp()
output “End of program”
return
7. a. The Some Interest Credit Company provides loans to customers at 1.5 percent
interest per month. Design an application that gets customer account data, including
an account number, customer name, and balance due. Output the account number and
name; then output the customer’s projected balance each month for the next 10
months. Assume that when the balance reaches $10 or less, the customer can pay off
the account. At the beginning of every month, 1.5 percent interest is added to the
balance, and then the customer makes a payment equal to 5 percent of the current
balance. Assume the customer makes no new purchases.
Answer:
A sample solution follows
Flowchart:
Programming Logic and Design, 6e Solutions 5-12
Pseudocode:
start
Declarations
num accountNum
num balanceDue
num month
num paymentAmt
string custName
Programming Logic and Design, 6e Solutions 5-13
housekeeping()
output PROMPT1
input accountNum
return
detail()
output PROMPT2
input custName, balanceDue
output accountNum, custName
month = 1
while month <= 10
balanceDue = balanceDue * (1 + INTEREST_RATE)
if balanceDue > 10 then
paymentAmt = balanceDue * PAY_RATE
balanceDue = balanceDue – paymentAmt
output month, balanceDue
month = month + 1
else
balanceDue = 0
output month, balanceDue
month = 11
endif
endwhile
output PROMPT1
input accountNum
return
finishUp()
output “End of program”
return
Answer:
A sample solution follows
Flowchart:
Programming Logic and Design, 6e Solutions 5-14
Pseudocode:
start
Declarations
Programming Logic and Design, 6e Solutions 5-15
num accountNum
num balanceDue
num month
num paymentAmt
string custName
num PAY_RATE = 0.05
num INTEREST_RATE = 0.015
string PROMPT1 = “Enter an account number or 999 to exit”
string PROMPT2 = “Enter the customer name and balance due”
housekeeping()
while accountNum not equal to 999
detailLoop()
endwhile
finishUp()
stop
housekeeping()
output PROMPT1
input accountNum
return
detailLoop()
output PROMPT2
input custName, balanceDue
output accountNum, custName
month = 1
while month <= 10
balanceDue = balanceDue * (1 + INTEREST_RATE)
if balanceDue > 10 then
paymentAmt = balanceDue * PAY_RATE
balanceDue = balanceDue – paymentAmt
output month, balanceDue
month = month + 1
else
balanceDue = 0
output month, balanceDue
month = 11
endif
endwhile
output PROMPT1
input accountNum
return
finishUp()
output “End of program”
return
8. Secondhand Rose Resale Shop is having a seven-day sale during which the price of
any unsold item drops 10 percent each day. For example, an item that costs $10.00 on
the first day costs 10 percent less, or $9.00, on the second day. On the third day, the
same item is 10 percent less than $9.00, or $8.10. Design an application that allows a
user to input a price until an appropriate sentinel value is entered. Output is the price
of every item on each day, one through seven.
Programming Logic and Design, 6e Solutions 5-16
Answer:
A sample solution follows
Flowchart:
Pseudocode:
start
Declarations
num itemNumber
num price
num day
string description
num TERM = 7
num REDUCTION = 0.10
string PROMPT1 = “Enter an item number or 999 to exit”
string PROMPT2 = “Enter the description and price”
housekeeping()
while itemNumber not equal to 999
detailLoop()
Programming Logic and Design, 6e Solutions 5-17
endwhile
finishUp()
stop
housekeeping()
output PROMPT1
input itemNumber
return
detailLoop()
output PROMPT2
input description, price
day = 0
while day < TERM
day = day + 1
output day, price
price = price * (1 – REDUCTION)
endwhile
output PROMPT1
input itemNumber
return
finishUp()
output “End of program”
return
9. The Howell Bank provides savings accounts that compound interest on a yearly basis.
In other words, if you deposit $100 for two years at 4 percent interest, at the end of
one year you will have $104. At the end of two years, you will have the $104 plus 4
percent of that, or $108.16. Design a program that accepts an account number, the
account owner’s first and last names, and a balance. The program operates
continuously until an appropriate sentinel value is entered for the account number.
Output the projected running total balance for each year for the next 20 years.
Answer:
A sample solution follows
Flowchart:
Programming Logic and Design, 6e Solutions 5-18
Pseudocode:
start
Declarations
num accountNum
num balance
num year
string firstName
string lastName
num INTEREST_RATE = 0.04
num TERM = 20
string PROMPT1 = “Enter an account number or 999 to exit”
string PROMPT2 = “Enter the first name, last name, and
balance”
housekeeping
while accountNum does not equal 999
detailLoop()
endwhile
finishUp()
stop
housekeeping()
output PROMPT1
Programming Logic and Design, 6e Solutions 5-19
input accountNum
return
detailLoop()
output PROMPT2
input firstName, lastName, balance
output accountNum, firstName, lastName
year = 0
while year < TERM
balance = balance * (1 + INTEREST_RATE)
year = year + 1
output year, balance
endwhile
output PROMPT1
input accountNum
return
finishUp()
output “End of program”
return
10. Mr. Roper owns 20 apartment buildings. Each building contains 15 units that he rents
for $800 per month each. Design the application that would print 12 payment coupons
for each of the 15 apartments in each of the 20 buildings. Each coupon should contain
the building number (1 through 20), the apartment number (1 through 15), the month
(1 through 12), and the amount of rent due.
Flowchart:
Programming Logic and Design, 6e Solutions 5-20
Pseudocode:
start
Declarations
num buildingNum
num aptNum
num month
num TOTAL_BUILDS = 20
num TOTAL_UNITS = 15
num TOTAL_MONTHS = 12
num RENT = 800
string COUPON_HEADING = “Payment Coupon”
housekeeping()
while buildingNum <= TOTAL_BUILDS
Programming Logic and Design, 6e Solutions 5-21
detailLoop()
endwhile
finishUp()
stop
housekeeping()
buildingNum = 1
return
detailLoop()
aptNum = 1
while aptNum <= TOTAL_UNITS
month = 1
while month <= TOTAL_MONTHS
output COUPON_HEADING
output “Building Number: “, buildingNum
output “Apartment Number: “, aptNum
output “Month: “, month
output “Rent Due: “, RENT
month = month + 1
endwhile
aptNum = aptNum + 1
endwhile
buildingNum = buildingNum + 1
return
finishUp()
output “End of program”
return
11. a. Design a program for the Hollywood Movie Rating Guide, in which users
continuously enter a value from 0 to 4 that indicates the number of stars they are
awarding to the Guide’s featured movie of the week. The program executes
continuously until a user enters a negative number to quit. If a user enters a star value
that does not fall in the correct range, reprompt the user continuously until a correct
value is entered. At the end of the program, display the average star rating for the
movie.
Flowchart:
Programming Logic and Design, 6e Solutions 5-22
Pseudocode:
start
Declarations
num numOfStars
num count = 0
num total = 0
num avg
string PROMPT =
“Enter the star rating or a negative number to quit”
housekeeping()
while numOfStars >= 0
detailLoop()
endwhile
finishUp()
stop
housekeeping()
output PROMPT
input numOfStars
return
Programming Logic and Design, 6e Solutions 5-23
detailLoop()
while numOfStars > 4 OR numOfStars < 0
output “Please enter a value from 0 to 4”
input numOfStars
endwhile
count = count + 1
total = total + numOfStars
output PROMPT
input numOfStars
return
finishUp()
avg = total / count
output “The average star rating is: ”, avg
output “End of program”
return
b. Modify the movie-rating program so that a user gets three tries to enter a valid
rating. After three incorrect entries, the program issues an appropriate message and
continues with a new user.
Flowchart:
Programming Logic and Design, 6e Solutions 5-24
Pseudocode:
start
Declarations
num numOfStars
num count = 0
num total = 0
num attempts
num avg
num LIMIT = 3
string PROMPT =
“Enter the star rating or a negative number to quit”
Programming Logic and Design, 6e Solutions 5-25
housekeeping()
while numOfStars >= 0 AND attempts < LIMITS
detailLoop()
endwhile
finishUp()
stop
housekeeping()
output PROMPT
input numOfStars
attempts = 0
return
detailLoop()
while (numOfStars > 4 OR numOfStars < 0) AND attempts < LIMIT
output “Please enter a value from 0 to 4”
input numOfStars
attempts = attempts + 1
endwhile
if attempts < LIMIT then
count = count + 1
total = total + numOfStars
output PROMPT
input numOfStars
else
output “You have failed to enter a valid rating.”
output “The program will now end.”
endif
return
finishUp()
avg = total / count
output “The average star rating is: ”, avg
output “End of program”
return
c. Modify the movie-rating program so that the user is prompted continuously for a
movie title until “ZZZZZ” is entered. Then, for each movie, continuously accept star-
rating values until a negative number is entered. Display the average rating for each
movie.
Flowchart:
Programming Logic and Design, 6e Solutions 5-26
Programming Logic and Design, 6e Solutions 5-27
Pseudocode:
start
Declarations
string movieTitle
num numOfStars
num count = 0
num total = 0
num attempts
num avg
num LIMIT = 3
string STAR_PROMPT =
“Enter a star rating or a negative number for a new movie”
string MOVIE_PROMPT =
“Enter a movie title or ZZZZZ to quit”
housekeeping()
while movieTitle not equal to “ZZZZZ” AND attempts < LIMITS
detailLoop()
endwhile
finishUp()
stop
housekeeping()
output MOVIE_PROMPT
input movieTitle
attempts = 0
return
detailLoop()
output STAR_PROMPT
input numOfStars
while numOfStars >= 0 AND attempts < LIMIT
getStarRating()
endwhile
calcAverage()
if attempts < LIMIT then
output MOVIE_PROMPT
input movieTitle
attempts = 0
endif
return
getStarRating()
while (numOfStars > 4 OR numOfStars < 0) AND attempts < LIMIT
output “Please enter a value from 0 to 4”
input numOfStars
attempts = attempts + 1
endwhile
if attempts < LIMIT then
count = count + 1
total = total + numOfStars
output PROMPT
input numOfStars
else
output “You have failed to enter a valid rating.”
output “The program will now end.”
Programming Logic and Design, 6e Solutions 5-28
endif
return
calcAverage()
avg = total / count
output “The average star rating for ”, movieTitle, “ is: ”, avg
return
finishUp()
output “End of program”
return
12. The Café Noir Coffee Shop wants some market research on its customers. When a
customer places an order, a clerk asks for the customer’s zip code and age. The clerk
enters that data as well as the number of items the customer orders. The program
operates continuously until the clerk enters a 0 for zip code at the end of the day.
When the clerk enters an invalid zip code (more than 5 digits) or an invalid age
(defined as less than 10 or more than 110), the program reprompts the clerk
continuously. When the clerk enters fewer than 1 or more than 12 items, the program
reprompts the clerk two more times. If the clerk enters a high value on the third
attempt, the program accepts the high value, but if the clerk enters a negative value on
the third attempt, an error message is displayed and the order is not counted. At the
end of the program, display a count of the number of items ordered by customers
from the same zip code as the coffee shop (54984), and a count from other zip codes.
Also display the average customer age, as well as counts of the number of items
ordered by customers under 30 and by customers 30 and older.
Pseudocode:
start
Declarations
num custZip
num custAge
num numItems = 0
num validNumItems
num countOfOrders = 0
num totalCustAge = 0
num numItemsUnder30 = 0
num numItems30AndOlder = 0
num numItemsInStoreZip = 0
num numItemsInOtherZips = 0
num STORE_ZIP = 54984
string ZIP_PROMPT = “Enter the zip code”
string AGE_PROMPT = “Enter the customer’s age”
string ITEM_PROMPT = “Enter the number of items”
housekeeping()
while custZip not equal to 0
detailLoop()
endwhile
Programming Logic and Design, 6e Solutions 5-29
finishUp()
stop
validateZipCode()
while custZip > 99999
output “Please enter a valid zip code”
input custZip
endwhile
return
validateCustAge()
while custAge < 10 OR custAge > 110
output “Please enter a valid customer age”
input custAge
endwhile
return
validateNumItems()
Declarations
num attempts = 0
num LIMIT = 2
validNumItems = 1
while (numItems < 1 OR numItems > 12) AND attempts < LIMIT
output “Please reenter the number of items”
input numItems
attempts = attempts + 1
endwhile
if attempts = 2 AND numItems < 0 then
output “An invalid number of items was entered”
output “This order will not be counted”
validNumItems = 0
endif
return
housekeeping()
output ZIP_PROMPT
input custZip
return
detailLoop()
output AGE_PROMPT
input custAge
output ITEM_PROMPT
input numItems
validateZipCode()
validateCustAge()
validateNumItems()
countOfOrders = countOfOrders + 1
totalCustAge = totalCustAge + custAge
if custZip = STORE_ZIP
numItemsInStoreZip = numItemsInStoreZip + numItems
else
numItemsInOtherZips = numItemsInOtherZips + numItems
endif
Programming Logic and Design, 6e Solutions 5-30
output ZIP_PROMPT
input custZip
return
finishUp()
Declarations
avgCustAge
if countOfOrders > 0 then
output “Total items ordered in the ”,
STORE_ZIP, “ zip code = ”, numItemsInStoreZip
output “Total items ordered in other zip codes = ”,
numItemsInOtherZips
avgCustAge = totalCustAge / countOfOrders
output “The average customer age is: ”, avgCustAge
output numItemsUnder30,
“ items were ordered by customers under 30”
output numItems30AndOlder,
“ items were ordered by customers 30 and older”
endif
output “End of program”
return
Flowchart: The flowchart’s structure will be very similar to that given for previous
exercises.
13. Your student disk contains files named DEBUG05-01.txt, DEBUG05-02.txt, and
DEBUG05-03.txt. Each file starts with some comments that describe the problem.
Comments are lines that begin with two slashes (//). Following the comments, each
file contains pseudocode that has one or more bugs you must find and correct.
Answer:
Game Zone
14. In Chapter 2, you learned that in many programming languages you can generate a
random number between 1 and a limiting value named LIMIT by using a statement
similar to randomNumber = random(LIMIT). In Chapter 4, you created the logic
for a guessing game in which the application generates a random number and the
Programming Logic and Design, 6e Solutions 5-31
player tries to guess it. Now, create the guessing game itself. After each guess, display
a message indicating whether the player’s guess was correct, too high, or too low.
When the player eventually guesses the correct number, display a count of the
number of guesses that were required.
Answer:
A sample solution is as follows:
Flowchart:
Pseudocode:
start
Declarations
num myRandomNumber
num guess
num count
num LIMIT
string PROMPT = “Enter a number between 1 and “
string CORRECT = “You guessed correctly!”
string HIGH = “You guessed too high!”
Programming Logic and Design, 6e Solutions 5-32
housekeeping()
myRandomNumber = random(LIMIT)
output PROMPT, LIMIT
input guess
count = 1
return
detailLoop()
if guess > myRandomNumber then
output HIGH
else
output LOW
endif
input guess
count = count + 1
return
finishUp()
output CORRECT
output “It took ”, count, “ guesses!”
output “End of program”
return
15. Create the logic for a game that simulates rolling two dice by generating two numbers
between 1 and 6 inclusive. The player chooses a number between 2 and 12 (the
lowest and highest totals possible for two dice). The player then “rolls” two dice up to
three times. If the number chosen by the user comes up, the user wins and the game
ends. If the number does not come up within three rolls, the computer wins.
Answer:
A sample solution is as follows:
Flowchart:
Programming Logic and Design, 6e Solutions 5-33
Pseudocode:
start
Declarations
num dice1
num dice2
Programming Logic and Design, 6e Solutions 5-34
num guess
num count
num won
num LIMIT = 6
string PROMPT = “Choose a number between 1 and 12“
string WIN = “You win!”
string LOSE = “You lose!”
housekeeping()
while count < 3 AND won = 0
detailLoop()
endwhile
finishUp()
stop
housekeeping()
count = 0
won = 0
dice1 = random(LIMIT)
dice2 = random(LIMIT)
output PROMPT
input guess
return
detailLoop()
count = count + 1
if guess = dice1 + dice2 then
output WIN
won = 1
endif
dice1 = random(LIMIT)
dice2 = random(LIMIT)
return
finishUp()
if count = 3 AND won = 0 then
output LOSE
endif
output “End of program”
return
16. Create the logic for the dice game Pig, in which a player can compete with the
computer. The object of the game is to be the first to score 100 points. The user and
computer take turns rolling a pair of dice following these rules:
On a turn, each player rolls two dice. If no 1 appears, the dice values are added to
a running total for the turn, and the player can choose whether to roll again or
pass the turn to the other player.
If a 1 appears on one of the dice, the player’s turn total becomes 0; in other words,
nothing more is added to the player’s game total for that turn, and it becomes the
other player’s turn.
If a 1 appears on both of the dice, not only is the player’s turn over, but the
player’s entire accumulated total is reset to 0.
Programming Logic and Design, 6e Solutions 5-35
When the computer does not roll a 1 and can choose whether to roll again,
generate a random value of 1 or 2. The computer will then decide to continue
when the value is 1 and decide to quit and pass the turn to the player when the
value is not 1.
Answer:
A sample solution is as follows:
Pseudocode:
start
Declarations
num dice1
num dice2
num userCount
num computerCount
num userTurn
num LIMIT = 2
num WIN_NUM =100
housekeeping()
while computerCount < WIN_NUM AND userCount < WIN_NUM
detailLoop()
endwhile
stop
housekeeping()
output ”The first to 100 wins the game of Pig”
userCount = 0
computerCount = 0
userTurn = 1
return
detailLoop()
if userTurn = 1 then
output “User’s turn to roll the dice”
else
output “Computer’s turn to roll the dice”
endif
dice1 = random(LIMIT)
dice2 = random(LIMIT)
if userTurn = 1 then
if dice1 = 1 OR dice2 = 1 then
output “Computer's turn”
userTurn = 0
if dice1 = 1 AND dice2 = 1 then
userCount = 0
endif
else
userCount = userCount + dice1 + dice2
if userCount >= WIN_NUM
output “User wins!”
else
output “Enter a 1 to play again or
0 to pass”
Programming Logic and Design, 6e Solutions 5-36
input userTurn
endif
endif
else
if dice1 = 1 OR dice2 = 1
output “User's turn”
userTurn = 1
if dice1 = 1 AND dice2 = 1 THEN
computerCount = 0
endif
else
computerCount = computerCount + dice1 + dice2
if computerCount >= WIN_NUM
output “Computer wins!”
else
if random(2) = 1 then
userTurn = 0
else
userTurn = 1
endif
endif
endif
endif
return
finishUp()
Flowchart: The flowchart’s structure will be very similar to that given for previous
exercises.
Up for Discussion
17. Suppose you wrote a program that you suspect is in an infinite loop because it just
keeps running for several minutes with no output and without ending. What would
you add to your program to help you discover the origin of the problem?
Answer:
18. Suppose you know that every employee in your organization has a seven-digit ID
number used for logging on to the computer system. A loop would be useful to guess
every combination of seven digits in an ID. Are there any circumstances in which you
should try to guess another employee’s ID number?
Programming Logic and Design, 6e Solutions 5-37
Answer:
19. If every employee in an organization had a seven-digit ID number, guessing all the
possible combinations would be a relatively easy programming task. How could you
alter the construction of employee IDs to make guessing them more difficult?
Answer: