ch06 logic6e solutions
DESCRIPTION
ProgramingTRANSCRIPT
Programming Logic and Design, 6e Solutions 6-
Programming Logic and Design, 6th Edition
Chapter 6
Exercises
1. a. Design the logic for a program that allows a user to enter 10 numbers, then displays them in the reverse order of their entry.
Answer:
A sample solution follows
Flowchart:
Pseudocode:
startDeclarations
num indexnum SIZE = 10num numbers[SIZE] = 0,0,0,0,0,0,0,0,0,0
1
Programming Logic and Design, 6e Solutions 6-
getReady()while index < SIZE
getNumbers()endwhilefinishUp()
stop
getReady()index = 0
return
getNumbers()output “Enter a number for position ”, indexinput numbers[index]index = index + 1
return
finishUp()output “The numbers in reverse order are: ”while index > 0
index = index – 1output numbers[index]
endwhilereturn
b. Modify the reverse-display program so that the user can enter up to 10 numbers until a sentinel value is entered.
Answer:
A sample solution follows
Flowchart:
2
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num indexnum SIZE = 10num numbers[SIZE] = 0,0,0,0,0,0,0,0,0,0string CONTINUE = “Y”string moreNumbers = CONTINUE
getReady()while index < SIZE AND moreNumbers equal to CONTINUE
getNumbers()endwhilefinishUp()
stop
getReady()index = 0output “Do you want to enter a number? (Y/N)”input moreNumbers
return
getNumbers()output “Enter a number for position ”, indexinput numbers[index]index = index + 1
3
Programming Logic and Design, 6e Solutions 6-
output “Do you want to enter more numbers? (Y/N)”input moreNumbers
return
finishUp()output “The numbers in reverse order are: ”while index > 0
index = index – 1output numbers[index]
endwhilereturn
2. a. Design the logic for a program that allows a user to enter 10 numbers, then displays each and its difference from the numeric average of the numbers.
Answer:
A sample solution follows
Flowchart:
4
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num indexnum sumnum avgnum SIZE = 10num numbers[SIZE] = 0,0,0,0,0,0,0,0,0,0
getReady()while index < SIZE
getNumbers()endwhilefinishUp()
stop
getReady()index = 0sum = 0
return
getNumbers()output “Enter a number for position ”, indexinput numbers[index]sum = sum + numbers[index]index = index + 1
return
finishUp()avg = sum/SIZEindex = 0while index < SIZE
output numbers[index], avg – numbers[index]index = index + 1
endwhilereturn
b. Modify the program in Exercise 2a so that the user can enter up to 10 numbers until a sentinel value is entered.
Answer:
A sample solution follows
Flowchart:
5
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num indexnum sumnum avgnum actualSizenum SIZE = 10num numbers[SIZE] = 0
6
Programming Logic and Design, 6e Solutions 6-
string CONTINUE = “Y”string moreNumbers = CONTINUE
getReady()while index < SIZE AND moreNumbers = CONTINUE
getNumbers()endwhilefinishUp()
stop
getReady()index = 0sum = 0output “Do you want to enter a number? (Y/N)”input moreNumbers
return
getNumbers()output “Enter a number for position ”, indexinput numbers[index]sum = sum + numbers[index]index = index + 1output “Do you want to enter more numbers? (Y/N)”input moreNumbers
return
finishUp()actualSize = indexif actualSize > 0 then
avg = sum/actualSizeindex = 0while index < actualSize
output numbers[index], avg – numbers[index]index = index + 1
endwhileendif
return
3. a. The city of Cary is holding a special census. The city has collected data on cards that each hold the voting district and age of a citizen. The districts are numbered 1 through 22, and residents’ ages range from 0 through 105. Design a program that allows a clerk to go through the cards, entering the district for each citizen until an appropriate sentinel value is entered. The output is a list of all 22 districts and the number of residents in each.
Answer:
A sample solution follows
Flowchart:
7
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num districtnum DIS_SIZE = 22
8
Programming Logic and Design, 6e Solutions 6-
num districtCnt[SIZE] = 0num QUIT = -1
getReady()while district not equal to QUIT
collectData()endwhilefinishUp()
stop
getReady()output “Enter a district number or ”, QUIT, “ to quit”input district
return
collectData()if district >= 1 AND district <= SIZE then
districtCnt[district-1] = districtCnt[district-1] + 1else
output “Invalid district, record not counted”endifoutput “Enter a district number or ”, QUIT, “ to quit”input district
return
finishUp()district = 0while district < DIS_SIZE
output district+1, districtCnt[district]district = district + 1
endwhilereturn
b. Modify Exercise 3a so the clerk enters both the district and age on each card. Produce a count of the number of residents in each of the 22 districts and a count of residents in each of the following age groups: under 18, 18 through 30, 31 through 45, 46 through 64, and 65 and older.
Answer:
A sample solution follows
Flowchart:
9
Programming Logic and Design, 6e Solutions 6-
num agenum districtnum xnum QUIT = -1num MAX_AGE = 105num AGE_SIZE = 5num ageCnt[SIZE] = 0num DIS_SIZE = 22num districtCnt[DIS_SIZE] = 0num AGE_RANGE = 0, 18, 31, 46, 65string AGE_GROUPS = “under 18”, “18 through 30”,
“31 through 45”, “46 through 64”, “65 and older”
getReady()while district not equal to QUIT
countAges()endwhilefinishUp()
stop
getReady()output “Enter a district number or ”, QUIT, “ to quit”input district
return
countAges()if district >= 1 AND district <= SIZE then
output “Enter the citizen’s age”input ageif age >=0 AND age <= MAX_AGE then
districtCnt[district-1] = districtCnt[district-1]+1x = AGE_SIZE – 1while age < AGE_RANGE[x]
x = x – 1endwhileageCnt[x] = ageCnt[x] + 1
elseoutput “Invalid age, record not counted”
endifelse
output “Invalid district, record not counted”endifoutput “Enter a district number or ”, QUIT, “ to quit”input district
return
finishUp()district = 0while district < DIS_SIZE
output district+1, districtCnt[district]district = district+1
endwhilex = 0while x < AGE_SIZE
output AGE_GROUPS[x], ageCnt[x]x = x + 1
endwhile
11
Programming Logic and Design, 6e Solutions 6-
return
4. a. The Midville Park District maintains five soccer teams, as shown in the table. Design a program that accepts a player’s team number and displays the player’s team name.
Team Number Team Name1 Goal Getters2 The Force3 Top Guns4 Shooting Stars5 Midfield Monsters
Answer:
A sample solution follows
Flowchart:
12
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num teamNumnum QUIT = -1num SIZE = 5string teams[SIZE] = “Goal Getters”, “The Force”,
“Top Guns”, “Shooting Stars”, “Midfield Monsters”
getReady()while teamNum not equal to QUIT
displayTeamName()endwhilefinishUp()
stop
getReady()output “Enter the player’s team number or ”, QUIT, “ to quit”input teamNum
return
displayTeamName()if teamNum >= 1 AND teamNum <= SIZE then
output teamNum, teams[teamNum-1]else
output “Invalid team number”endifoutput “Enter the player’s team number or ”, QUIT, “ to quit”input teamNum
return
finishUp()output “End of program”
return
b. Modify the Midville Park District program so that after the last player has been entered, the program displays a count of the number of players registered for each.
Answer:
A sample solution follows
Flowchart:
13
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num teamNumnum QUIT = -1num SIZE = 5num teamCnt[SIZE] = 0string teams[SIZE] = “Goal Getters”, “The Force”,
“Top Guns”, “Shooting Stars”, “Midfield Monsters”
getReady()while teamNum not equal to QUIT
countTeams()endwhilefinishUp()
14
Programming Logic and Design, 6e Solutions 6-
stop
getReady()output “Enter the player’s team number or ”, QUIT, “ to quit”input teamNum
return
countTeams()if teamNum >= 1 AND teamNum <= SIZE then
output teamNum, teams[teamNum-1]teamCnt[teamNum-1] = teamCnt[teamNum-1] + 1
elseoutput “Invalid team number”
endifoutput “Enter the player’s team number or ”, QUIT, “ to quit”input teamNum
return
finishUp()teamNum = 0while teamNum < SIZE
output teamNum+1, teamCnt[teamNum]teamNum = teamNum + 1
endwhilereturn
5. a. Watson Elementary School contains 30 classrooms numbered 1 through 30. Each classroom can contain any number of students up to 35. Each student takes an achievement test at the end of the school year and receives a score from 0 through 100. Write a program that accepts data for each student in the school—student ID, classroom number, and score on the achievement test. Design a program that lists the total points scored for each of the 30 classrooms.
Answer:
A sample solution follows
Flowchart:
15
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num stuIDnum classNumnum scorenum SIZE = 30num QUIT = 9999num totalPnts[SIZE] = 0
getReady()while stuID not equal to QUIT
collectStudentData()endwhilefinishUp()
stop
16
Programming Logic and Design, 6e Solutions 6-
getReady()output “Enter a student ID or ”, QUIT, “ to quit”input stuID
return
collectStudentData()output “Enter the classroom number and score for student ”, stuIDinput classNum, scoreif classNum >= 1 AND classNum <= SIZE then
totalPnts[classNum-1] = totalPnts[classNum-1] + scoreelse
output “Invalid classroom number”endifoutput “Enter a student ID or ”, QUIT, “ to quit”input stuID
return
finishUp()classNum = 0while classNum < SIZE
output classNum+1, totalPnts[classNum]classNum = classNum + 1
endwhilereturn
b. Modify the Watson Elementary School program so that each classroom’s average of the test scores is output, rather than each classroom’s total.
Answer:
A sample solution follows
Flowchart:
17
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num stuIDnum classNumnum score
18
Programming Logic and Design, 6e Solutions 6-
num avgnum SIZE = 30num QUIT = 9999num totalPnts[SIZE] = 0num classCnt[SIZE] = 0
getReady()while stuID not equal to QUIT
collectStudentData()endwhileclassNum = 0finishUp()
stop
getReady()output “Enter a student ID or ”, QUIT, “ to quit”input stuID
return
collectStudentData()output “Enter the classroom number and score for student ”, stuIDinput classNum, scoreif classNum >= 1 AND classNum <= SIZE then
totalPnts[classNum-1] = totalPnts[classNum-1] + scoreclassCnt[classNum-1] = classCnt[classNum-1] + 1
elseoutput “Invalid classroom number”
endifoutput “Enter a student ID or ”, QUIT, “ to quit”input stuID
return
finishUp()while classNum < SIZE
if classCnt[classNum] = 0 then avg = 0else avg =totalPnts[classNum]/classCnt[classNum]endifoutput classNum+1, avgclassNum = classNum + 1
endwhilereturn
6. The Billy Goat Fast-Food restaurant sells the following products:
Product Price ($)Cheeseburger 2.49Pepsi 1.00Chips 0.59
Design the logic for an application allows a user to enter an order item continuously until a sentinel value is entered. After each item, display its price or the message
19
Programming Logic and Design, 6e Solutions 6-
“Sorry, we do not carry that” as output. After all items have been entered, display the total price for the order.
Answer:
A sample solution follows
Flowchart:
20
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
string itemOrderednum xnum found = 0num total = 0num SIZE = 3string QUIT = “ZZZZ”num PRICE[SIZE] = 2.49, 1, 0.59string PRODUCT[SIZE] = “Cheeseburger”, “Pepsi”, “Chips”string ERROR_MSG = “Sorry, we do not carry that”
getReady()while itemOrdered not equal to QUIT
detailLoop()endwhile finishUp()
stop
getReady()output “Enter an item or ”, QUIT, “ to complete your order”input itemOrdered
return
detailLoop()found = 0x = 0while x < SIZE
if itemOrdered = PRODUCT[x] thenoutput PRICE[x]x = SIZEfound = 1total = total + PRICE[x]
elsex = x + 1
endifendwhileif found = 0 then
output ERROR_MSGendifoutput “Enter an item or ”, QUIT, “ to complete your order”input itemOrdered
return
finishUp()output “Your order total is: $”, total
return
7. Design the application logic for a company that wants a report containing a breakdown of payroll by department. Input includes each employee’s department number, hourly salary, and number of hours worked. The output is a list of the seven departments in the company and the total gross payroll (rate times hours) for each department. The department names are shown in the accompanying table.
22
Programming Logic and Design, 6e Solutions 6-
Department Number
Department Name
1 Personnel2 Marketing3 Manufacturing4 Computer Services5 Sales6 Accounting7 Shipping
Answer:
A sample solution follows
Flowchart:
23
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num deptNumnum salarynum hrsWorkednum SIZE = 7num totalGross[SIZE] = 0string DEPTS[SIZE] = “Personnel”, “Marketing”,
“Manufacturing”, “Computer Services”, “Sales”, “Accounting”, “Shipping”
24
Programming Logic and Design, 6e Solutions 6-
getReady()while not eof
detailLoop()endwhile finishUp()
stop
getReady()output “Enter the department number, hourly salary, and number of
hours worked”input deptNum, salary, hrsWorked
return
detailLoop()if deptNum >= 1 AND deptNum <= SIZE then
totalGross[deptNum-1] = totalGross[deptNum-1] + (hrsWorked * salary)
elseoutput “Invalid department number”
endifoutput “Enter the department number, hourly salary, and number of
hours worked”input deptNum, salary, hrsWorked
return
finishUp()deptNum = 0while deptNum < SIZE
output deptNum+1, DEPTS[deptNum], totalGross[deptNum]deptNum = deptNum + 1
endwhilereturn
8. Design a program that computes pay for employees. Allow a user to continuously input employees’ names until an appropriate sentinel value is entered. Also input each employee’s hourly wage and hours worked. Compute each employee’s gross pay (hours times rate), withholding tax percentage (based on the accompanying table), withholding tax amount, and net pay (gross pay minus withholding tax). Display all the results for each employee. After the last employee has been entered, display the sum of all the hours worked, the total gross payroll, the total withholding for all employees, and the total net payroll.
Weekly Gross Pay Withholding Percent (%)0.00 – 200.00 10
200.01 – 350.00 14350.01 – 500.00 18500.01 – up.000 22
Answer: A sample solution follows
Flowchart:
25
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
string empNamenum salary
26
Programming Logic and Design, 6e Solutions 6-
num hrsWorkednum xnum grossPaynum withTaxnum netPaynum totalGrossPay = 0num totalHrsWorked = 0num totalWithTax = 0num totalNetPay = 0string QUIT = “zzzz”num SIZE = 4num WITH_RATE[SIZE] = 0.10, 0.14, 0.18, 0.22num WITH_RANGE[SIZE] = 0, 200.01, 350.01, 500.01
getReady()while empName not equal to QUIT
detailLoop()endwhile finishUp()
stop
getReady()output “Enter an employee name or ”, QUIT, “ to quit”input empName
return
detailLoop()output “Enter ”, empName, “’s hourly wage and hours worked”input salary, hoursWorkedgrossPay = hrsWorked * salarytotalHrsWorked = totalHrsWorked + hrsWorkedtotalGrossPay = totalGrossPay + grossPayx = SIZE – 1while grossPay < WITH_RANGE[x]
x = x – 1endwhilewithTax = grossPay * WITH_RATE[x]totalWithTax = totalWithTax + withTaxnetPay = grossPay – withTaxtotalNetPay = totalNetPay + netPayoutput empName, grossPay, WITH_RATE[x] * 100, withTax, netPayoutput “Enter an employee name or ”, QUIT, “ to quit”input empName
return
finishUp()output totalHrsWorked, totalGrossPay, totalWithTax, totalNetPay
return
27
Programming Logic and Design, 6e Solutions 6-
9. The Perfect Party Catering Company hosts events for clients. Create an application that accepts an event number, the event host’s last name, and numeric month, day, and year values representing the event date. The application should also accept the number of guests that will attend the event and a numeric meal code that represents the entrée the event hosts will serve. As each client’s data is entered, verify that the month, day, year, and meal code are valid; if any of these is not valid, continue to prompt the user until it is. The valid meal codes are shown in the accompanying table.
Code Entrée Price per Person ($)1 Roast beef 24.502 Salmon 19.003 Linguine 16.504 Chicken 18.00
Design the logic for an application that outputs each event number, host name, validated date, meal code, entrée name, number of guests, gross total price for the party, and price for the party after discount. The gross total price for the party is the meal price per guest times the number of guests. The final price includes a discount based on the accompanying table.
Number of Guests Discount ($)1-25 026-50 7551-100 125101-250 200251 and over 300
Answer: A sample solution follows
Flowchart:
28
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num eventNumstring lastNamenum monthnum daynum year
29
Programming Logic and Design, 6e Solutions 6-
num numOfGuestsnum mealCodenum xnum invalidDate = 0num grossPricenum MSIZE = 4num DSIZE = 5string ENTREES[MSIZE] = “Roast beef”, “Salmon”, “Linguine”,
“Chicken”num PRICE[MSIZE] = 24.50, 19, 16.50, 18num DIS_RANGE[DSIZE] = 1, 26, 51, 101, 251num DISCOUNT[DSIZE] = 0, 75, 125, 200, 300
getReady()detail()finishUp()
stop
getReady()output “Enter the event number, host’s last name, and event date
(as month, day, and year)”input eventNum, lastName, month, day, yearoutput “Enter the number of guests and the meal code”input numOfGuests, mealCode
return
detail()validateMealCode()validateDate()grossPrice = PRICE[mealCode-1] * numOfGuestsx = DSIZE – 1while numOfGuests < DIS_RANGE[x]
x = x – 1endwhileoutput eventNum, lastName, month, “/”, day, “/”, year,
mealCode, ENTREES[mealCode-1], numOfGuests, grossPrice, (grossPrice – DISCOUNT[x])
return
validateMealCode()while mealCode < 1 OR mealCode > MSIZE
output “Invalid meal code, please reenter”input mealCode
endwhilereturn
validateDate()checkDate()while invalidDate = 1
ouput “Invalid date, please reenter”input month, day, year
endwhile return
checkDate()invalidDate = 0if (month < 1 OR month > 12 OR day < 1 OR day > 31 OR
year < 2009 OR year > 2012) then
30
Programming Logic and Design, 6e Solutions 6-
invalidDate = 1else
if day = 31 AND (month = 4 OR month = 6 OR month = 9 OR month = 11) theninvalidDate = 1
elseif day > 28 AND month = 2 then
invalidDate = 1endif
endifendif
return
finishUp()output “End of program”
return
10. a. Daily Life Magazine wants an analysis of the demographic characteristics of its readers. The Marketing department has collected reader survey records containing the age, gender, marital status, and annual income of readers. Design an application that accepts reader data and, when data entry is complete, produces a count of readers by age groups as follows: under 20, 20–29, 30–39, 40–49, and 50 and older.
Answer: A sample solution follows
Flowchart:
31
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num agenum incomenum xstring genderstring maritalStatusnum SIZE = 5num ageCnt[SIZE] = 0
32
Programming Logic and Design, 6e Solutions 6-
num AGE_RANGE[SIZE] = 0, 20, 30, 40, 50string AGE_GROUPS[SIZE] = “under 20”, “20 through 29”,
“30 through 39”, “40 through 49”, “50 and older”
getReady()while not eof
detailLoop()endwhilefinishUp()
stop
getReady()output “Enter the age, gender, marital status, and income of a
reader”input age, gender, maritalStatus, income
return
detailLoop()x = SIZE – 1while age < AGE_RANGE[x]
x = x – 1endwhileageCnt[x] = ageCnt[x] + 1output “Enter the age, gender, marital status, and income of a
reader”input age, gender, maritalStatus, income
return
finishUp()x = 0while x < SIZE
output AGE_GROUPS[x], ageCnt[x]x = x + 1
endwhilereturn
b. Modify the Daily Life Magazine program so that it produces a count of readers by gender within age group—that is, under 20 females, under 20 males, and so on.
Answer: A sample solution follows
Flowchart:
33
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num agenum incomenum xstring genderstring maritalStatusnum SIZE = 5
34
Programming Logic and Design, 6e Solutions 6-
num maleCnt[SIZE] = 0num femaleCnt[SIZE] = 0num AGE_RANGE[SIZE] = 0, 20, 30, 40, 50string AGE_GROUPS[SIZE] = “under 20”, “20 through 29”,
“30 through 39”, “40 through 49”, “50 and older”
getReady()while not eof
detailLoop()endwhilefinishUp()
stop
getReady()output “Enter the age, gender, marital status, and income of a
reader”input age, gender, maritalStatus, income
return
detailLoop()x = SIZE – 1while age < AGE_RANGE[x]
x = x – 1endwhileif gender = “male” then
maleCnt[x] = maleCnt[x] + 1else
femaleCnt[x] = femaleCnt[x] + 1endifoutput “Enter the age, gender, marital status, and income of a
reader”input age, gender, maritalStatus, income
return
finishUp()x = 0while x < SIZE
output AGE_GROUPS[x], maleCnt[x], femaleCnt[x]x = x + 1
endwhilereturn
c. Modify the Daily Life Magazine program so that is produces a count of readers by annual income groups as follows: under $30,000, $30,000–$49,999, 50,000–$69,999, and $70,000 and up.
Answer: A sample solution follows
Flowchart:
35
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num agenum incomenum xstring genderstring maritalStatusnum SIZE = 4num incomeCnt[SIZE] = 0num INCOME_RANGE[SIZE] = 0, 30000, 50000, 70000
36
Programming Logic and Design, 6e Solutions 6-
string INCOME_GROUPS[SIZE] = “under $30,000”, “$30,000-$49,999”, “$50,000-
$69,999”, “$70,000 and up”
getReady()while not eof
detailLoop()endwhilefinishUp()
stop
getReady()output “Enter the age, gender, marital status, and income of a
reader”input age, gender, maritalStatus, income
return
detailLoop()x = SIZE – 1while age < INCOME_RANGE[x]
x = x – 1endwhileincomeCnt[x] = incomeCnt[x] + 1output “Enter the age, gender, marital status, and income of a
reader”input age, gender, maritalStatus, income
return
finishUp()x = 0while x < SIZE
output INCOME_GROUPS[x], incomeCnt[x]x = x + 1
endwhilereturn
11. Glen Ross Vacation Property Sales employs seven salespeople, as shown in the accompanying table.
ID Number Salesperson Name103 Darwin104 Kratz201 Shulstad319 Fortune367 Wickert388 Miller435 Vick
When a salesperson makes a sale, a record is created including the date, time, and dollar amount of the sale. The time is expressed in hours and minutes, based on a 24-hour clock. The sale amount is expressed in whole dollars. Salespeople earn a commission that differs for each sale, based on the rate schedule in the accompanying table.
37
Programming Logic and Design, 6e Solutions 6-
Sale Amount ($) Commission Rate (%)0 – 50,999 451,000 - 125,999 5126,000 - 200,999 6201,000 and up 7
Design an application that produces each of the following:
a. A list of each salesperson number, name, total sales, and total commissions
Answer: A sample solution follows
Flowchart:
38
Programming Logic and Design, 6e Solutions 6-
startDeclarations num date num hours
num minutesnum saleAmtnum idNumnum personnum xstring datenum SSIZE = 4num PSIZE = 7num totalSales[PSIZE] = 0num totalComm[PSIZE] = 0num ID_NUM[PSIZE] = 103, 104, 201, 319, 367, 388, 435string NAME[PSIZE] = “Darwin”, “Kratz”, “Shulstad”, “Fortune”,
“Wickert”, “Miller”, “Vick”num SALE_AMT[SSIZE] = 0, 51000, 126000, 201000num COMM_RATE[SSIZE] = 0.04, 0.05, 0.06, 0.07
getReady()while not eof
detailLoop()endwhilefinishUp()
stop
getReady()output “Enter the salesperson ID number”input idNum
return
detailLoop()person = 0while person < PSIZE AND idNum not equal to ID_NUM[person]
person = person + 1endwhileif person = PSIZE then
output “An invalid number has been entered, please try again”
elseinput date, hours, minutes, saleAmttotalSales[person] = totalSales[person] + saleAmtx = SSIZE – 1while saleAmt < SALE_AMT[x]
x = x – 1endwhiletotalComm[person] = totalComm[person] +
(COMM_RATE[x] * saleAmt)endifoutput “Enter the salesperson ID number”input idNum
return
finishUp()x = 0while x < PSIZE
output ID_NUM[x], NAME[x], totalSales[x], totalComm[x]
40
Programming Logic and Design, 6e Solutions 6-
x = x + 1endwhile
return
b. A list of each each month of the year as both a number and a word (for example, “01 January”), and the total sales for the month for all salespeople
Answer: A sample solution follows
Flowchart:
41
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations num hours, minutes
num month, day, year
42
Programming Logic and Design, 6e Solutions 6-
num saleAmtnum idNumnum person, xnum SSIZE = 4num PSIZE = 7num MSIZE = 12num totalSales[MSIZE] = 0num totalComm[PSIZE] = 0num ID_NUM[PSIZE] = 103, 104, 201, 319, 367, 388, 435string NAME[PSIZE] = “Darwin”, “Kratz”, “Shulstad”, “Fortune”,
“Wickert”, “Miller”, “Vick”num SALE_AMT[SSIZE] = 0, 51000, 126000, 201000num COMM_RATE[SSIZE] = 0.04, 0.05, 0.06, 0.07
string MONTHS[MSIZE] = “January”, “February”, “March” “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”
getReady()while not eof
detailLoop()endwhilefinishUp()
stop
getReady()output “Enter the salesperson ID number”input idNum
return
detailLoop()person = 0while person < PSIZE AND idNum not equal to ID_NUM[person]
person = person + 1endwhileif person = PSIZE then
output “An invalid number has been entered, please try again”
elseinput month, day, year, hours, minutes, saleAmtwhile month < 1 OR month > 12 OR day < 1 OR day > 31
output “Invalid date, please reenter”input month, day, year
endwhiletotalSales[month-1] = totalSales[month-1] + saleAmtendif
output “Enter the salesperson ID number”input idNum
return
finishUp()x = 0while x < MSIZE
output x+1, MONTHS[x], totalSales[x]x = x + 1
endwhilereturn
43
Programming Logic and Design, 6e Solutions 6-
c. A list of total sales as well as total commissions earned by all salespeople for each of the following time frames, based on hour of the day: 00–05, 06–12, 13–18, and 19–23
Answer: A sample solution follows
Flowchart: The flowchart will be similar to those shown in parts a and b.
Pseudocode:
startDeclarations
num hours, minutesnum month, day, yearnum saleAmtnum idNumnum time, xnum SSIZE = 4num PSIZE = 7num TSIZE = 4num totalSales[TSIZE] = 0num totalComm[TSIZE] = 0num ID_NUM[PSIZE] = 103, 104, 201, 319, 367, 388, 435string NAME[PSIZE] = “Darwin”, “Kratz”, “Shulstad”, “Fortune”,
“Wickert”, “Miller”, “Vick”num SALE_AMT[SSIZE] = 0, 51000, 126000, 201000num COMM_RATE[SSIZE] = 0.04, 0.05, 0.06, 0.07num TIME_RANGE[TSIZE] = 0, 6, 13, 19string TIMES[TSIZE] = “00-05", “06-12”, “13-18”, “19-23”
getReady()while not eof
detailLoop()endwhilefinishUp()
stop
getReady()output “Enter the salesperson ID number”input idNum
return
detailLoop()person = 0while person < PSIZE AND idNum not equal to ID_NUM[person]
person = person + 1endwhileif person = PSIZE then
output “An invalid number has been entered, please try again”
elseinput month, day, year, hours, minutes, saleAmt
44
Programming Logic and Design, 6e Solutions 6-
while month < 1 OR month > 12 OR day < 1 OR day > 31output “Invalid date, please reenter”input month, day, year
endwhiletime = TSIZE-1while hours < TIME_RANGE[time]
time = time – 1endwhiletotalSales[time] = totalSales[time] + saleAmtx = SSIZE – 1while saleAmt < SALE_AMT[x]
x = x – 1endwhiletotalComm[time] = totalComm[time] + (COMM_RATE[x]*saleAmt)
endifoutput “Enter the salesperson ID number”input idNum
return
finishUp()x = 0while x < TSIZE
output TIME[x], totalSales[x], totalComm[x]x = x + 1
endwhilereturn
Find the Bugs
12. Your student disk contains files named DEBUG06-01.txt, DEBUG06-02.txt, and DEBUG06-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:
Please see the DEBUG06-01.txt, DEBUG06-02.txt, and DEBUG06-03.txt solution files.
Game Zone
13. Create the logic for a Magic 8 Ball game in which the user enters a question such as “What does my future hold?” The computer randomly selects one of eight possible vague answers, such as “It remains to be seen.”
startDeclarations
num LIMIT = 8
45
Programming Logic and Design, 6e Solutions 6-
num indexstring userQuestionstring QUIT = “zzzz”string ANSWERS[LIMIT] =
“As I see it, yes”, “It is certain”,“Signs point to yes”,“It remains to be seen”, “Reply hazy, try again”,“Outlook not so good”,“Cannot predict now”,“My sources say no”
getReady()while userQuestion <> QUIT
detailLoop()endwhilefinishUp()
stop
getReady()output “Enter a question or ”, QUIT, “ to quit”input userQuestion
return
detailLoop()index = random(LIMIT)output ANSWERS[index]output “Enter a question or ”, QUIT, “ to quit”input userQuestion
return
finishUp()output “End of program”
return
14. Create the logic for an application that contains an array of 10 multiple-choice questions related to your favorite hobby. Each question contains three answer choices. Also create a parallel array that holds the correct answer to each question—A, B, or C. Display each question and verify that the user enters only A, B, or C as the answer—if not, keep prompting the user until a valid response is entered. If the user responds to a question correctly, display “Correct!”; otherwise, display “The correct answer is” and the letter of the correct answer. After the user answers all the questions, display the number of correct and incorrect answers.
Answer:
A sample solution follows
Pseudocode (Please note, for brevity this solution contains only five questions. Students should provide 10 questions.):
start
46
Programming Logic and Design, 6e Solutions 6-
Declarationsnum correct = 0num incorrect = 0num xnum SIZE = 5string guesses[SIZE] = “”string QUESTIONS[SIZE] =
“What is the closest star to Earth?”, “What is the name of Earth’s moon?”, “How many miles (in trillions) are in a light year?”, “How many moons does Pluto have?”, “What planet is the biggest?”
string CHOICES[SIZE] = “A. Scopper, B. Dipper, C. Sun”, “A. Luna, B. Europa, C. Sol”, “A. 6, B. 93, C. 10”,“A. 6, B. 2, C. 3”, “A. Saturn, B. Jupiter, C. Earth”
string ANSWERS[SIZE] = “C”, “A”, “A”, “C”, “B”getReady()while x < SIZE
detailLoop()endwhilefinishUp()
stop
getReady()x = 0output QUESTIONS[x], CHOICES[x]input guesses[x]
return
detailLoop()while (guesses[x] not equal to “A” OR
guesses[x] not equal to “B” ORguesses[x] not equal to “C”)output “Invalid answer, please enter either A, B, or C”input guesses[x]
endwhileif guesses[x] = ANSWERS[x] then
output “Correct!”correct = correct + 1
elseoutput “The correct answer is: “, ANSWERS[x]incorrect = incorrect + 1
endifx = x + 1output QUESTIONS[x], CHOICES[x]input guesses[x]
return
finishUp()output “Number of correct = ”, correctoutput “Number of incorrect = ”, incorrect
return
47
Programming Logic and Design, 6e Solutions 6-
15. a. Create the logic for a dice game. The application randomly “throws” five dice for the computer and five dice for the player. As each random throw, store it in an array. The application displays all the values, which can be from 1 to 6 inclusive for each die. Decide the winner based on the following hierarchy of die values. Any higher combination beats a lower one; for example, five of a kind beats four of a kind.
Five of a kind Four of a kind Three of a kind A pair
For this game, the numeric dice values do not count. For example, if both players have three of a kind, it’s a tie, no matter what the values of the three dice are. Additionally, the game does not recognize a full house (three of a kind plus two of a kind). Figure 6-19 shows how the game might be played in a command-line environment.
Answer:
A sample solution follows
Pseudocode:
startDeclarations
num xnum ynum playerMatchnum computerMatchnum playerLargestnum computerLargestnum LIMIT = 6num SIZE = 5num playerDice[SIZE] = 0num computerDice[SIZE] = 0num playerValues[LIMIT] = 0num computerValues[LIMIT] = 0
getReady()accumulateNums()findLargest()finishUp()
stop
getReady()// populate both arrays with random numbersx = 0while x < SIZE
playerDice[x] = random(LIMIT)computerDice[x] = random(LIMIT)x = x + 1
endwhile
48
Programming Logic and Design, 6e Solutions 6-
// output what the computer rolledx = 0output “Computer rolled: ”while x < SIZE
output computerDice[x]x = x + 1
endwhile
// output what player rolledx = 0output “You rolled: ”while x < SIZE
output playerDice[x]x = x + 1
endwhilereturn
acculateNums()// accumulate how many of each number was rolled// by both the computer and the player, store these// values in arraysx = 0while x < LIMIT
y = 0while y < SIZE
if playerDice[y] = (x+1) thenplayerValues[x] = playerValues[x] + 1
endifif computerDice[y] = (x+1) then
computerValues[x] = computerValues[x] + 1endify = y + 1
endwhilex = x + 1
endwhilereturn
findLargest()// find the largest accumulated value – this will tell the // program the largest “of a kind”x = 0computerLargest = 0playerLargest = 0while x < LIMIT-1
if computerValues[x+1] > computerValues[computerLargest] computerLargest = x + 1
endifif playerValues[x+1] > playerValues[playerLargest]
playerLargest = x + 1endifx = x + 1
endwhile
computerMatch = computerValues[computerLargest]playerMatch = playerValues[playerLargest]
return
49
Programming Logic and Design, 6e Solutions 6-
finishUp()output “Computer has ”, computerMatch, “ of a kind”output “You have ”, playerMatch, “ of a kind”
if computerMatch > playerMatch thenoutput “Computer wins”
elseif playerMatch > computerMatch then
output “You win”else
output “Tie”endif
endifreturn
b. Improve the dice game so that when both players have the same combination of dice, the higher value wins. For example, two 6s beats two 5s.
Answer:
A sample solution follows
Pseudocode:start
Declarationsnum xnum ynum playerMatchnum computerMatchnum playerLargestnum computerLargestnum LIMIT = 6num SIZE = 5num playerDice[SIZE] = 0num computerDice[SIZE] = 0num playerValues[LIMIT] = 0num computerValues[LIMIT] = 0
getReady()accumulateNums()findLargest()finishUp()
stop
getReady()x = 0while x < SIZE
playerDice[x] = random(LIMIT)computerDice[x] = random(LIMIT)x = x + 1
endwhile
x = 0output “Computer rolled: ”
50
Programming Logic and Design, 6e Solutions 6-
while x < SIZEoutput computerDice[x]x = x + 1
endwhile
x = 0output “You rolled: ”while x < SIZE
output playerDice[x]x = x + 1
endwhilereturn
accumulateNums()x = 0while x < LIMIT
y = 0while y < SIZE
if playerDice[y] = x + 1 thenplayerValues[x] = playerValues[x] + 1
endifif computerDice[y] = x + 1 then
computerValues[x] = computerValues[x] + 1endify = y + 1
endwhilex = x + 1
endwhilereturn
findLargest()x = 0computerLargest = 0playerLargest = 0while x < LIMIT-1
if computerValues[x+1] > computerValues[computerLargest] computerLargest = x + 1
endifif playerValues[x+1] > playerValues[playerLargest]
playerLargest = x + 1endifx = x + 1
endwhile
computerMatch = computerValues[computerLargest]playerMatch = playerValues[playerLargest]
return
finishUp()output “Computer has ”, computerMatch, “ of a kind”output “You have ”, playerMatch, “ of a kind”
if computerMatch > playerMatch thenoutput “Computer wins”
elseif playerMatch > computerMatch then
output “You win”
51
Programming Logic and Design, 6e Solutions 6-
elseif computerLargest > playerLargest then
output “Computer wins”else
if playerLargest > computerLargest thenoutput “You win”
elseoutput “Tie”
endifendif
endifendif
return
16. Design the logic for the game Hangman, in which the user guesses letters in a hidden word. Store the letters of a word in an array of characters. Display a dash for each missing letter. Allow the user to continuously guess a letter until all the letters in the word are correctly guessed. As the user enters each guess, display the word again, filling in the guess if it was correct. For example, if the hidden word is “computer”, first display “--------”. After the user guesses “p”, the display becomes “---p----”. Make sure that when a user makes a correct guess, all the matching letters are filled in. For example, if the word is “banana” then when the user guesses “a”, all three “a” characters are filled in.
Answer:
A sample solution follows
Pseudocode:
startDeclarations
num xnum numCorrectnum LENGTH = 8string WORD[LENGTH] = “C”, “O”, “M”, “P”, “U”,
“T”, “E”, “R”string hiddenWord[LENGTH] = “-”,“-”,“-”,“-”,
“-”,“-”,“-”,“-”string guess
getReady()while numCorrect not equal to LENGTH
detailLoop()endwhilefinishUp()
stop
getReady()numCorrect = 0output hiddenWordoutput “Please guess a letter”input guess
return
52
Programming Logic and Design, 6e Solutions 6-
detailLoop()x = 0while x < LENGTH
if WORD[x] = guess thennumCorrect = numCorrect + 1hiddenWord[x] = guess
endifx = x + 1
endwhileoutput hiddenWordif numCorrect not equal to LENGTH
output “Please guess a letter”input guess
endifreturn
finishUp()output “You guessed the word!”output hiddenWord
return
17. Create two parallel arrays that represent a standard deck of 52 playing cards. One array is numeric and holds the values 1 through 13 (representing Ace, 2 through 10, Jack, Queen, and King). The other array is a string array and holds suits (“Clubs”, “Diamonds”, “Hearts”, and “Spades”). Create the arrays so that all 52 cards are represented. Create a War card game that randomly selects two cards (one for the player and one for the computer) and declares a winner (or a tie) based on the numeric value of the two cards. The game should play for 26 rounds of War, dealing a full deck with no repeated cards. For this game, assume the lowest card is the Ace. Display the values of the player’s and computer’s cards, compare their values, and determine the winner. When all the cards in the deck are exhausted, display a count of the number of times the player wins, the number of times the computer wins, and the number of ties.
Here are some hints:
Start by creating an array of all 52 playing cards. Select a random number for the deck position of the player’s first card and assign
the card at that array position to the player. Move every higher-positioned card in the deck “down” one to fill in the gap. In
other words, if the player’s first random number is 49, select the card at position 49 (both the numeric value and the string), move the card that was in position 50 to position 49, and move the card that was in position 51 to position 50. Only 51 cards remain in the deck after the player’s first card is dealt, so the available card array is smaller by one.
In the same way, randomly select a card for the computer and “remove” the card from the deck.
Answer: A sample solution follows
53
Programming Logic and Design, 6e Solutions 6-
Pseudocode:
startDeclarations
num xnum ynum limitnum indexnum playerCardnum playerCardNumnum computerCardnum computerCardNumnum playerWin = 0num computerWin = 0num tie = 0string playerCardSuitstring computerCardSuitnum LENGTH = 52num GROUPS = 4num ROUNDS = 26num BOUNDS[GROUPS] = 0, 13, 26, 39num cards[LENGTH] =
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52
string SUITS[GROUPS] = “Clubs”,“Diamonds”,“Hearts”,“Spades”getReady()while y < ROUNDS
detailLoop()endwhilefinishUp()
stop
getReady()limit = LENGTHy = 0
return
detailLoop()// input the player’s cardindex = random(limit)playerCard = cards[index]x = GROUPS-1while playerCard < BOUNDS[x]
x = x – 1endwhileplayerCardNum = playerCard – BOUNDS[x]playerCardSuit = SUITS[x]
// move the cards up (take out player card)x = indexwhile x < (limit – 1)
cards[x] = cards[x+1]x = x + 1
endwhile
54
Programming Logic and Design, 6e Solutions 6-
limit = limit – 1
// input the computer’s cardindex = random(limit)computerCard = cards[index]x = GROUPS-1while computerCard < BOUNDS[x]
x = x – 1endwhilecomputerCardNum = computerCard – BOUNDS[x]computerCardSuit = SUITS[x]
// move the cards up (take out computer’s card)x = indexwhile x < (limit – 1)
cards[x] = cards[x+1]x = x + 1
endwhilelimit = limit – 1output “Player’s card: ”, playerCardNum, “ of ”, playerCardSuit
output “Computer’s card: ”, computerCardNum, “ of ”, computerCardSuit
if playerCardNum > computerCardNumoutput “Player wins hand!”playerWin = playerWin + 1
elseif computerCardNum > playerCardNum
output “Computer wins hand!”computerWin = computerWin + 1
elseoutput “Tie!”tie = tie + 1
endifendif
y = y + 1return
finishUp()output “End of game”
return
Up for Discussion
18. A train schedule is an everyday, real-life example of an array. Think of at least four more.
Answer:
Student answers will vary but might include: tax table
55
Programming Logic and Design, 6e Solutions 6-
life expectancy table based on year of birth insurance company height and weight table loan amortization schedule company salary schedule instructor’s grading scale shipping charges based on distance sliding fees for a service based on income
19. Every element in an array always has the same data type. Why is this necessary?
Answer:
Every element in an array has the same data type which forces every element in an array to be the same size in bytes. Therefore, it becomes possible to use a subscript to evenly measure an element's distance from the start of an array. For example, if you use a data type that occupies exactly four bytes of memory then the array element at subscript 0 is 0 bytes away from the beginning of the array, the element at subscript 1 is 4 bytes away, the element at subscript 2 is 8 bytes away, and so on.
56