Extended Prelude to Programming



Extended Prelude to Programming

Third Edition

Solutions to Selected Programming Problems

for the Instructor

Chapter 1

Problem 2

Declare Price, Tip As Real

Write “Enter the price of the meal.”

Input Price

Set Tip = 0.15 * Price

Write “Price of the meal: ”, Price

Write “Amount of the tip: ”, Tip

Problem 3

Declare C, F As Real

Write “Enter a temperature in degrees Celsius.”

Input C

Set F = (9 / 5) * C + 32

Write “Temperature in degrees Celsius: ”, C

Write “Temperature in degrees Fahrenheit: ”, F

Problem 4

Declare AtBats, Hits As Integer

Declare Average As Real

Write “Enter the number of at bats.”

Input AtBats

Write “Enter the number of at hits.”

Input Hits

Set Average = Hits / AtBats

Write “At bats: ”, AtBats

Write “Hits: ”, Hits

Write “Batting average: ”, Average

Problem 5

Declare P, R, T, I, FV As Real

Write “Enter the amount to be invested.”

Input P

Write “Enter the rate of interest as a decimal.”

Input R

Write “Enter the term of the investment (in years).”

Input T

Set I = P * R * T

Set FV = P + I

Write “The amount invested: ”, P, “ dollars”

Write “The rate of interest: ”, R * 100, “%”

Write “The term of the investment: ”, T, “ years”

Write “The future value: ”, FV, “ dollars”

Problem 6

Declare FirstName, LastName, FullName As String

Declare MiddleInitial As Character

Write “Enter the first name.”

Input FirstName

Write “Enter the middle initial.”

Input MiddleInitial

Write “Enter the last name.”

Input LastName

Set FullName = FirstName + “ ” + MiddleInitial + “. ” + LastName

Write “The full name is”

Write FullName

Chapter 2

Problem 1

Main module

Declare Sales, PercentRate, Commission As Real

Write “Commission Calculator”

Call Input Data module

Call Process Data module

Call Output Results module

End Program

Input Data module

Write “Enter the sales total for the month.”

Input Sales

Write “Enter the commission rate as a percentage.”

Input PercentRate

Process Data module

Declare Rate As Real

Set Rate = PercentRate / 100

Set Commission = Sales * Rate

Output Results module

Write “Sales for the month: ”, Sales, “ dollars”

Write “Commission rate: ”, PercentRate, “%”

Write “Commission for the month: ”, Commission, “ dollars”

Problem 2

Main module

Declare Name As String

Declare Pounds, Ounces As Integer

Declare Price, Unit Price As Real

Write “Unit Price Conversion Program”

Call Input Data module

Call Process Data module

Call Output Results module

End Program

Input Data module

Write “Enter the name of the item.”

Input Name

Write “Enter the price of the item.”

Input Price

Write “Enter the weight in pounds, ounces.”

Input Pounds, Ounces

Process Data module

Declare TotalOunces As Integer

Set TotalOunces = 16 * Pounds + Ounces

Set UnitPrice = Price / TotalOunces

Output Results module

Write “Item: ”, Name

Write “Price: $”, Price

Write “Weight: ”, Pounds, “ pounds, ”, Ounces, “ounces”

Write “Unit price: ”, UnitPrice

Problem 4

Main module

Declare ID As String

Declare PayRate, RegularHours, OvertimeHours As Real

Declare GrossPay, Deductions, NetPay As Real

Write “Employee Pay Program”

Call Input Data module

Call Process Data module

Call Output Results module

End Program

Input Data module

Write “Enter the employee’s ID number.”

Input ID

Write “Enter the employee’s rate of pay.”

Input PayRate

Write “Enter the hours worked: regular, overtime”

Input RegularHours, OvertimeHours

Write “Enter the employee’s deductions.”

Input Deductions

Process Data module

Set GrossPay = PayRate * (RegularHours + 1.5 * OvertimeHours)

Set NetPay = GrossPay - Deductions

Output Results module

Write “Employee ID and pay rate: ”, ID, “ $”, PayRate, “ per hour”

Write “Hours worked (regular/overtime): ”, RegularHours, “/”, OvertimeHours

Write “Gross pay: $”, GrossPay

Write “Deductions: $”, Deductions

Write “Net pay: $”, NetPay

Problem 6

Main module

Declare LoanAmount, PercentRate, MonthlyPayment As Real

Declare NumberOfPayments As Integer

Write “Monthly Payment Calculator”

Call Input Data module

Call Process Data module

Call Output Results module

End Program

Input Data module

Write “Input the amount of the loan.”

Input LoanAmount

Write “Enter the rate of interest as a percentage.”

Input PercentRate

Write “Enter the number of payments to be made.”

Input NumberOfPayments

Process Data module

Declare Rate, Power As Real

Set Rate = PercentRate / 100

Set Power = (1 + Rate) ^ NumberOfPayments

Set MonthlyPayment = LoanAmount * Rate* Power / (Power - 1)

Output Results module

Write “Amount of loan: $”, LoanAmount

Write “Rate of interest: ”, PercentRate, “%”

Write “Number of payments: ”, NumberOfPayments

Write “Monthly payment: $”, MonthlyPayment

Chapter 3

Problem 1

Main module

Declare Number As Real

Call Input Number module

Call Display Message module

End Program

Input Number module

Write “Enter a number.”

Input Number

Display Message module

If Number > 0 Then

Write “Positive”

End If

If Number < 0 Then

Write “Negative”

End If

If Number = 0 Then

Write “Neither Positive or Negative”

End If

Problem 2

Main module

Declare Num1, Num2 As Real

Declare Choice As Integer

Write “Basic Calculator”

Call Input Data module

Call Input Choice module

Select Case Of Choice

Case 0:

Write “Goodbye”

Case 1:

Call Display Sum module

Case 2:

Call Display Difference module

Case 3:

Call Display Product module

Case 4:

Call Display Quotient module

End Case

End Program

Input Data module

Write “Enter two numbers.”

Input Num1, Num2

Input Choice module

Write “0 - Quit program”

Write “1 - Display sum”

Write “2 - Display difference”

Write “3 - Display product”

Write “4 - Display quotient”

Input Choice

Display Sum module

Declare Sum As Real

Set Sum = Num1 + Num2

Write “The sum of ”, Num1, “ and ”, Num2, “ is:”

Write Sum

Display Difference module

Declare Difference As Real

Set Difference = Num1 - Num2

Write “The difference of ”, Num1, “ and ”, Num2, “ is:”

Write Difference

Display Product module

Declare Product As Real

Set Product = Num1 * Num2

Write “The product of ”, Num1, “ and ”, Num2, “ is:”

Write Product

Display Quotient module

Declare Quotient As Real

If Num2 0 Then

Set Quotient = Num1 / Num2

Write “The quotient of ”, Num1, “ and ”, Num2, “ is:”

Write Quotient

Else

Write “No quotient -- Divisor is 0"

End If

Problem 4

Main module

Declare X, Area As Real

Declare Choice As Integer

Write “Area Calculator”

Call Input Data module

Call Input Choice module

Select Case Of Choice

Case 0:

Write “Goodbye”

Case 1:

Call Square module

Case 2:

Call Circle module

Case 3:

Call Triangle module

End Case

End Program

Input Data module

Write “Enter a positive number for”

Write “the side of a square or equilateral triangle”

Write “or the radius of a circle.”

Input X

Input Choice module

Write “0 - Quit program”

Write “1 - Compute area of square”

Write “2 - Compute area of circle”

Write “3 - Compute area of equilateral triangle”

Input Choice

Square module

Set Area = X ^ 2

Write “The area of a square with side ”, X

Write “ is: ”, Area

Circle module

Set Area = 3.14 * X ^ 2

Write “The area of a circle with radius ”, X

Write “ is: ”, Area

Triangle module

Set Area = (Sqrt(3) / 4) * X ^ 2

Write “The area of an equilateral triangle with side ”, X

Write “ is: ”, Area

Problem 6

Main module

Declare Income, Tax As Real

Call Input Income module

Call Compute Tax module

Call Display Tax module

End Program

Input Income module

Write “Enter your taxable income.”

Input Income

Compute Tax module

If (Income >= 0) And (Income < 50000) Then

Set Tax = 0.05 * Income

End If

If (Income >= 50000) And (Income < 100000) Then

Set Tax = 2500 + 0.07 * Income

End If

If Income >= 100000 Then

Set Tax = 6000 + 0.09 * Income

End If

Display Tax module

Write “Income: ”, Income

Write “Tax: ”, Tax

Problem 7

[See Chapter 4, Problem 7 solution]

Problem 8

[See Chapter 4, Problem 8 solution]

Chapter 4

Problem 1

Main module

Declare MySquare As Real

Write “Table of Squares”

Call Input Number module

Call Display Table module

End Program

Input Number module

Write “Enter a positive number.”

Write “The program will display the squares of”

Write “the numbers from 1 to this number and the sum of the squares.”

Input MySquare

While MySquare 0

Set Counter = Counter + 1

Set Sum = Sum + Age

End While

Display Average module

Declare Average As Real

If Counter 0 Then

Set Average = Sum / Counter

Write “The average age is ”, Average, “ years.”

Else

Write “No ages were entered.”

End If

Problem 3

Main module

Declare N, NFactorial As Integer

Write “Factorial Calculator”

Call Input Number module

Call Compute Factorial module

Call Display Result module

End Program

Input Number module

Declare Num As Real

Repeat

Write “Enter a positive integer.”

Input Num

Until (Num > 0) And (Int(Num) = Num)

Set N = Num

Compute Factorial module

Declare Product, K As Integer

Set Product = 1

For K = 1 Step 1 Until N

Set Product = Product * K

End For

Set NFactorial = Product

Display Result module

Write N, “! = ”, NFactorial

Problem 5

Main module

Declare P As Real

Write “Bacteria Population”

Call Input Initial Number module

Call Display Table module

End Program

Input Initial Number module

Write “Enter the number of bacteria present initially.”

Input P

While P 0

If Number > Max Then

Set Max = Number

End If

Write “Enter a positive number. Enter 0 when done.”

Input Number

End While

Display Maximum module

Write “The largest number input is”

Write Maximum

Problem 8

Main module

Declare PositiveSum, NegativeSum As Real

Write “Positive/Negative Sum Calculator”

Call Find Sums module

Call Display Sums module

End Program

Find Sums module

Declare Number As Real

Set PositiveSum = 0

Set NegativeSum = 0

Write “Enter a number. Enter 0 when done.”

Input Number

While Number 0

If Number > 0 Then

Set PositiveSum = PositiveSum + Number

Else

Set NegativeSum = NegativeSum + Number

End If

Write “Enter a number. Enter 0 when done.”

Input Number

End While

Display Sums module

Write “The sum of the positive numbers is ”, PositiveSum

Write “The sum of the negative numbers is ”, NegativeSum

Chapter 5

Problem 1

Main module

Declare Numbers[100] Of Reals

Declare Max, Min As Real

Declare Count As Integer

Write “Maximum and Minimum Values”

Call Input Numbers module

Call Find MaxMin module

Call Display MaxMin module

End Program

Input Numbers module

Declare Num As Real

Set Count = 0

Write “Enter a number. Enter 0 to quit.”

Input Num

While Num 0

Set Numbers[Count] = Num

Set Count = Count + 1

Write “Enter a number. Enter 0 to quit.”

Input Num

End While

Find MaxMin module

Declare K As Integer

Set Max = Numbers[0]

Set Min = Numbers[0]

For K = 1 Step 1 To Count - 1

If Numbers[K] > Max Then

Set Max = Numbers[K]

End If

If Numbers[K] < Min Then

Set Min = Numbers[K]

End If

End For

Display MaxMin module

Declare K As Integer

Write “Given the numbers:”

For K = 0 Step 1 To Count - 1

Write Numbers[K]

End For

Write “The largest is ”, Max

Write “The smallest is ”, Min

Problem 2

Main module

Declare X[100] Of Reals

Declare Mean, StandardDeviation As Real

Declare Count As Integer

Write “Mean and Standard Deviation”

Call Input Numbers module

Call Compute Results module

Call Display Results module

End Program

Input Numbers module

Declare Num AS Real

Set Count = 0

Write “Enter a number. Enter 0 to quit.”

Input Num

While Num 0

Set X[Count] = Num

Set Count = Count + 1

Write “Enter a number. Enter 0 to quit.”

Input Num

End While

Compute Results module

Declare Sum As Real

Declare K As Integer

If Count 0

Set Sum = 0

For K = 0 Step 1 To Count - 1

Set Sum = Sum + X[K]

End For

Set Mean = Sum / Count

If Count = 1 Then

Set StandardDeviation = 0

Else

Set Sum = 0

For K = 0 Step 1 To Count - 1

Set Sum = Sum + (X[K] - Mean) ^ 2

End For

Set StandardDeviation = Sqrt(Sum / (Count - 1))

End If

End If

Display Results module

If Count = 0 Then

Write “No numbers were input.”

Else

Write “The mean is ”, Mean

Write “The standard deviation is ”, StandardDeviation

End If

Problem 4

Main module

Declare Prices[100] Of Reals

Declare Median As Real

Declare Count As Integer

Write “Median Home Price”

Call Input Prices module

Call Sort Prices module

Call Compute Median module

Call Display Median module

End Program

Input Prices module

Declare Price As Real

Set Count = 0

Write “Enter the price of a home. Enter 0 to quit.”

Input Price

While Price 0

Set Prices[Count] = Num

Set Count = Count + 1

Write “Enter the price of a home. Enter 0 to quit.”

Input Price

End While

Sort Prices module

Declare Flag As Integer

Declare Temp As Real

Set Flag = 0

While Flag = 0

Set Flag = 1

For K = 0 Step 1 To Count - 2

If Prices[K] > Prices[K + 1] Then

Set Prices[K] = Temp

Set Prices[K] = Prices[K + 1]

Set Prices[K + 1] = Temp

Set Flag = 0

End If

End For

End While

Compute Median module

If Count/2 Int(Count/2) Then

Set Median = Prices[(Count + 1)/2]

Else

Set Median = (Prices[Count/2] + Prices[Count/2 + 1]) / 2

End If

Display Median module

Write “The median price of the homes n Botany Bay is”

Write “$”, Median

Problem 5

Main module

Declare A[4, 4] Of Integers

Declare IsMagicSquare As Integer

Write “Test for a Magic Square”

Call Input Square module

Call Test Square module

Call Display Result module

End Program

Input Square module

Declare I, J As Integer

Write “Enter the rows of a square array; 4 numbers per row.”

For I = 0 Step 1 To 3

Write “Row”, I

For J = 0 Step 1 To 3

Write “Number”, J

Input A[I, J]

End For (I)

End For (J)

Test Square module

Declare Sum, TestSum As Integer

Declare K As Integer

Set IsMagicSquare = 1

Set Sum = A[1, 1] + A[1, 2] + A[1, 3] + A[1, 4]

For K = 2 Step 1 To 4

Set TestSum = A[K, 1] + A[K, 2] + A[K, 3] + A[K, 4]

If Sum TestSum Then

Set IsMagicSquare = 0

End If

End For

For K = 1 Step 1 To 4

Set TestSum = A[1, K] + A[2, K] + A[3, K] + A[4, K]

If Sum TestSum Then

Set IsMagicSquare = 0

End If

End For

Set TestSum = A[1, 1] + A[2, 2] + A[3, 3] + A[4, 4]

If Sum TestSum Then

Set IsMagicSquare = 0

End If

Set TestSum = A[4, 1] + A[3, 2] + A[2, 3] + A[1, 4]

If Sum TestSum Then

Set IsMagicSquare = 0

End If

Display Result module

If IsMagicSquare = 1 Then

Write “This IS a magic square.”

Else

Write “This is NOT a magic square.”

End If

Problem 6

Declare FirstName, LastName, Phone As String

Declare Customer As String

Declare Found As Integer

Write “Phone Number Finder”

Open “CUSTOMER” For Input As DataFile

Write “Enter customer’s last name.”

Input Customer

Set Found = 0

While Not EOF(DataFile) AND Found = 0

Read DataFile, LastName, FirstName, Phone

If LastName = Customer Then

Write FirstName, “ ”, LastName, “ ”, Phone

Set Found = 1

End If

End While

If Found = 0 Then

Write Customer, “ was not found.”

End If

Close DataFile

Problem 8

Main module

Declare DriverName, LicenseNumber As String

Declare NumberTickets As Integer

Declare Names[10000], Licenses[10000] Of Strings

Declare Tickets[10000] Of Integers

Declare Count As Integer

Write “Driver License Database”

Open “LICENSES” For Input As LicensesFile

Call Load Licenses File module

Call Process User Request module

Close LicensesFile

End Program

Load Licenses module

Set Count = 0

While Not EOF(LicensesFile)

Set Count = Count + 1

Read LicensesFile, Names[Count], Licenses[Count], Tickets[Count]

End While

Process User Request module

Declare Driver As String

Declare Found, Index As Integer

Declare Response As Character

Write “Do you want to enter a driver license? (Y/N)”

Input Response

While Response = “Y” Or Response = “y”

Call Input License Number module

Call Find Driver Info module

Call Display Results module

Write “Do you want to enter a driver license? (Y/N)”

Input Response

End While

Input Driver License module

Write “Enter the driver’s license number.”

Input Driver

Find Driver Info module

Set Index = 0

Set Found = 0

While Found = 0 AND Index < Count

Set Index = Index + 1

If Licenses[Index] = Driver Then

Set Found = 1

End If

End While

Display Results module

If Found = 1 Then

Write Names[Index], “ - ”, Licenses[Index]

Write “Number of tickets: ”, Tickets[Index]

Else

Write Driver, “ not found”

End If

Chapter 6

Problem 1

Declare Name As String

Write “This program creates the file GRADES with records:”

Write “ Name, Test 1 Test 2 Test 3”

Open “GRADES” For Output As GradeFile

Write “Enter a student name. Enter ZZZ when done.”

Input Name

While Name “ZZZ”

Write GradeFile, Name, 0, 0, 0

Write “Enter a student name. Enter ZZZ when done.”

Input Name

End While

Close GradeFile

Problem 2

Declare Name As String

Declare Test1, Test2, Test3, Sum As Real

Write “This program displays the contents of the file GRADES.”

Open “GRADES” For Input As GradeFile

Write “Name, Test 1 Test 2 Test3 Total”

While Not EOF(GradeFile)

Read GradeFile, Name, Test1, Test2, Test3

Set Sum = Test1 + Test2 + Test3

Write Name, Test1, Test2, Test3, Sum

End While

Close GradeFile

Problem 3

Main module

Declare Name As String

Declare Test1, Test2, Test3, Sum As Real

Declare Choice As Integer

Open “GRADES” For Input As GradeFile

Write “Student Grades Display”

Call Input Choice module

If Choice = 1 Then

Call Display Single Student Record module

Else

Call Display All Student Records module

End If

Close GradeFile

End Program

Input Choice module

Repeat

Write “Enter 1 or 2.”

Write “1: Display a single student’s grades”

Write “2: Display all student grades”

Input Choice

Until (Choice = 1) Or (Choice = 2)

Display Single Student Record module

Declare Student As String

Write “Enter the student’s name.”

Input Student

Write “Name Test 1 Test 2 Test3 Total”

While Not EOF(GradeFile)

Read GradeFile, Name, Test1, Test2, Test3

If Student = Name Then

Set Sum = Test1 + Test2 + Test3

Write Name, Test1, Test2, Test3, Sum

End If

End While

Display All Student Records module

Write “Name Test 1 Test 2 Test3 Total”

While Not EOF(GradeFile)

Read GradeFile, Name, Test1, Test2, Test3

Set Sum = Test1 + Test2 + Test3

Write Name, Test1, Test2, Test3, Sum

End While

Problems 4, 5, 6

[This program combines the solutions to Problems 4, 5, and 6 into a single menu-driven

program.]

Main module

Declare PartNum, Quantity, Choice As Integer

Declare PartName As String

Open “INVENTORY” For Input As DataFile

Open “SCRATCH” For Output As TempFile

Write “Inventory Management”

Call Input Choice module

If Choice = 1 Then

Call Delete Record module

End If

If Choice = 2 Then

Call Modify Record module

End If

If Choice = 3 Then

Call Add Record module

End If

End Program

Input Choice module

Repeat

Write “Enter 1, 2, or 3.”

Write “1: Delete a part from the inventory”

Write “2: Modify a part in the inventory”

Write “3: Add a part to the inventory”

Input Choice

Until (Choice = 1) Or (Choice = 2) Or (Choice = 3)

Delete Record module

Declare Part As Integer

Write “Enter the part number for the part to be deleted.”

Input Part

While Not EOF(DataFile)

Read DataFile, PartNum, PartName, Quantity

If PartNum Part Then

Write TempFile, PartNum, PartName, Quantity

End If

End While

Close DataFile, TempFile

Copy SCRATCH onto INVENTORY

Modify Record module

Declare Part, NewQuantity As Integer

Write “Enter the part number and new quantity.”

Input Part, NewQuantity

While Not EOF(DataFile)

Read DataFile, PartNum, PartName, Quantity

If PartNum = Part Then

Write TempFile, PartNum, PartName, NewQuantity

End If

End While

Close DataFile, TempFile

Copy SCRATCH onto INVENTORY

Add Record module

Declare NewPart, NewQuantity As Integer

Declare NewName As String

Write “Enter the new part number, name, and quantity.”

Input NewPart, NewName, NewQuantity

Set Done = 0

While Not EOF(DataFile)

Read DataFile, PartNum, PartName, Quantity

If PartNum > NewPart Then

Write TempFile, NewPart, NewName, NewQuantity

Set Done = 1

End If

Write TempFile, PartNum, PartName, Quantity

End While

If Done = 0 Then

Write TempFile, NewPart, NewName, NewQuantity

End If

Close DataFile, TempFile

Copy SCRATCH onto INVENTORY

Chapter 7

Problem 1

Main

Declare Max As Real

Declare Count As Integer

Declare Numbers[100] Of Reals

Write “This program finds the largest of the numbers input.”

Call InputData(Numbers, Count)

Set Max = Largest(Numbers, Count)

Call OutputResult(Max)

End Program

Subprogram InputData(Numbers As Ref, Count As Ref)

Declare Num As Real

Set Count = 0

Write “Enter a positive number. Enter 0 to quit.”

Input Num

While Num > 0

Set Numbers[Count] = Num

Set Count = Count + 1

End While

End Subprogram

Function Largest(Numbers, Count) As Real

Declare K As Integer

Declare CurrentMax As Real

If Count = 0 Then

Set Largest = 0

Else

Set CurrentMax = Numbers[0]

For K = 1 Step 1 To Count - 1

If Numbers[K] > CurrentMax Then

Set CurrentMax = Numbers[K]

End If

End For

Set Largest = CurrentMax

End If

End Function

Subprogram OutputResult(Max)

If Max > 0 Then

Write “The largest number is ”, Max

Else

Write “No numbers were input.”

End If

End Subprogram

Problem 2

Main

Declare Mean As Real

Declare Count As Integer

Declare Numbers[100] Of Reals

Write “This program finds the mean of the numbers input.”

Call InputData(Numbers, Count)

Set Mean = Average(Numbers, Count)

Call OutputResult(Mean)

End Program

Subprogram InputData(Numbers As Ref, Count As Ref)

Declare Num As Real

Set Count = 0

Write “Enter a positive number. Enter 0 to quit.”

Input Num

While Num > 0

Set Numbers[Count] = Num

Set Count = Count + 1

End While

End Subprogram

Function Average(Numbers, Count) As Real

Declare K As Integer

Declare Sum As Real

If Count = 0 Then

Set Average = 0

Else

Set Sum = 0

For K = 0 Step 1 To Count - 1

Set Sum = Sum + Numbers[K]

End For

Set Average = Sum / Count

End If

End Function

Subprogram OutputResult(Mean)

If Count > 0 Then

Write “The mean of the numbers is ”, Mean

Else

Write “No numbers were input.”

End If

End Subprogram

Problem 3

Main

Declare DriverName, LicenseNumber As String

Declare NumberTickets As Integer

Declare Names[10000], Licenses[10000] Of Strings

Declare Tickets[10000] Of Integers

Declare Count As Integer

Write “Driver License Database”

Open “DRIVERLIST” For Input As LicensesFile

Call LoadFile(Count, Licenses, Names, Tickets)

Call InputLicense(DriverName)

Call Search(LicenseNumber, Count, Licenses, Names, Tickets,

Found, DriverName, NumberTickets)

Call DisplayResults(Found, DriverName, LicenseNumber, NumberTickets)

Close LicensesFile

End Program

Subprogram LoadFile(Count As Ref, Licenses As Ref, Names As Ref, Tickets As Ref)

Set Count = 0

While NOT EOF(LicensesFile)

Read LicensesFile, Names[Count], Licenses[Count], Tickets[Count]

Set Count = Count + 1

End While

End Subprogram

Subprogram InputLicense(LicenseNumber As Ref)

Write “Enter the driver’s license number.”

Input LicenseNumber

End Subprogram

Subprogram Search(LicenseNumber, Count, Licenses, Names, Tickets,

Found As Ref, DriverName As Ref, NumberTickets As Ref)

Declare Index As Integer

Set Index = 0

Set Found = 0

While Found = 0 AND Index < Count

If Licenses[Index] = LicenseNumber Then

Set Found = 1

Set DriverName = Names[Index]

Set NumberTickets = Tickets[Index]

End If

Set Index = Index + 1

End While

End Subprogram

Subprogram DisplayResults(Found, DriverName, LicenseNumber, NumberTickets)

If Found = 1 Then

Write DriverName, “ - ”, LicenseNumber

Write “Number of tickets: ”, NumberTickets

Else

Write DriverName, “ not found.”

End If

End Subprogram

Problem 5

Main

Declare Text[100] Of Characters

Declare NumberWords As Integer

Write “this program determines the number of words in the sentence input.”

Call InputSentence(Text)

Set NumberWords = CountWords(Text)

Call OutputResult(Text, NumberWords)

End Program

Subprogram InputSentence(Text As Ref)

Write “type a sentence and press Enter.”

Input Text

End Subprogram

Function CountWords(Text) As Integer

Declare K, NumWords As Integer

Set NumWords = 1

For K = 1 Step 1 To Length(Text)

If Text[K] = “ ” Then

Set Numwords = NumWords + 1

End If

End For

Set CountWords = NumWords

End Function

Subprogram OutputResult(Text, NumberWords)

Write “The number of words in the sentence”

Write Text

Write “is ”, NumberWords

End Subprogram

Problem 8

Main

Declare N, NFactorial As Integer

Write “When you enter a positive integer, this program will compute:”

Write “N! = 1 x 2 x 3 x . . . x N”

Call InputN(N)

Set NFactorial = Factorial(N)

Call OutputResult(N, NFactorial)

End Program

Subprogram InputN(N As Ref)

Declare Num As Real

Write “Enter a positive integer.”

Input Num

While (Num < 1) OR (Int(Num) Num)

Write “The number entered must be a positive integer.”

Write “Please reenter.”

Input Num

End While

Set N = Num

End Subprogram

Function Factorial(N) As Integer

If N = 1 Then

Set Factorial = 1

Else

Set Factorial = N * Factorial(N - 1)

End If

End Function

Subprogram OutputResult(N, NFactorial)

Write N, “! = ”, NFactorial

End Subprogram

Chapter 8

Problem 1

Class Worker

Hours As Real

Rate As Real

Total As Real

Subprogram SetHours(NewHours)

Set Hours = NewHours

End Subprogram

Subprogram SetRate(NewRate)

Set Rate = NewRate

End Subprogram

Subprogram ComputeTotal()

Set Total = Rate * Hours

End Subprogram

Function GetTotal() As Real

Set GetTotal = Total

End Function

End Class

Main

Declare Worker1 As Worker

Declare HoursWorked, PayRate As Real

Write “Enter an employee’s hours worked and hourly pay rate”

Write “and this program will compute his or her total wages.”

Write “To quit, enter 0 for both hours worked and pay rate.”

Write “Enter the number of hours worked:”

Input HoursWorked

Write “Enter the employee’s rate of pay:”

Input PayRate

While HoursWorked 0 AND PayRate 0

Call Worker1.SetHours(HoursWorked)

Call Worker1.SetRate(PayRate)

Call puteTotal()

Write “Total pay for this employee:”, Worker1.GetTotal()

Write “Enter the number of hours worked:”

Input HoursWorked

Write “Enter the employee’s rate of pay:”

Input PayRate

End While

End Program

Program 2

Class Tax

Income As Real

TaxDue As Real

Subprogram SetIncome(NewIncome)

Set Income = NewIncome

End Subprogram

Subprogram ComputeTax()

If Income 50000 And Income < 100000 Then

Set TaxDue = 2500 + .07 (Income - 50000)

Else

Set TaxDue = 6000 + .11 * (Income - 100000)

End If

End If

End Subprogram

Function GetTax() As Real

Set GetTax = TaxDue

End Function

End Class

Main

Declare Tax1 As Tax

Declare Income As Real

Write “Enter an income; this program will compute the tax due.”

Write “To quit, enter 0.”

Input Income

While Income > 0

Call Tax1.SetIncome(Income)

Call puteTax()

Write “Tax due = $”, GetTax()

Write “Enter an income; enter 0 to quit.”

Input Income

End While

End Program

Problem 3

Window

Name = MainWindow

Title = “Greeting”

Text Box

Name = GreetingBox

Text = “Hello”

Left Command Button

Name = RespondButton

Caption = “Respond”

Subprogram RespondButton.Click()

Set GreetingBox.Text = “Goodbye”

Set RespondButton.Enabled = False

End Subprogram

Right Command Button

Name = DoneButton

Caption = “Done”

Subprogram DoneButton.Click()

Call MainWindow.Close

End Program

End Subprogram

Problem 4

Window

Name = MainWindow

Title = “Temperature Conversion”

Top option button:

Name = Option1

Caption = “Convert Fahrenheit to Celsius”

Value = True

Subprogram Option1.Click()

Set Option1.Value = True

Set Option2.Value = False

Set FahrenheitBox.Enabled = True

Set CelsiusBox.Enabled = False

End Subprogram

Bottom option button:

Name = Option2

Caption = “Convert Celsius to Fahrenheit”

Value = False

Subprogram Option2.Click()

Set Option1.Value = False

Set Option2.Value = True

Set FahrenheitBox.Enabled = False

Set CelsiusBox.Enabled = True

End Subprogram

Left Label

Text = “Degrees Fahrenheit:”

Right Label

Text = “Degrees Celsius:”

Left Text Box

Name = FahrenheitBox

Text = “”

Subprogram FahrenheitBox.Click()

Set FahrenheitBox.Text = “”

End Subprogram

Subprogram FahrenheitBox.Change()

Set ConvertButton.Enabled = True

End Subprogram

Right Text Box

Name = CelsiusBox

Text = “”

Enabled = False

Subprogram CelsiusBox.Click()

Set CelsiusBox.Text = “”

End Subprogram

Subprogram CelsiusBox.Change()

Set ConvertButton.Enabled = True

End Subprogram

Left Command Button

Name = ConvertButton

Caption = “Convert”

Enabled = False

Subprogram ConvertButton.Click()

If Option1.Value = True Then

Set CelsiusBox.Enabled = True

Set CelsiusBox.Text = (5 / 9) * (Val(FahrenheitBox.Text) - 32)

Set CelsiusBox.Enabled = False

Else

Set FahrenheitBox.Enabled = True

Set FahrenheitBox.Text = (9 / 5) * Val(CelsiusBox.Text) + 32

Set FahrenheitBox.Enabled = False

End If

Set ConvertButton.Enabled = False

End Subprogram

Right command button:

Name = DoneButton

Caption = “Done”

Subprogram DoneButton.Click()

End Program

End Subprogram

Problem 5

Window

Name = MainWindow

Title = “Enter Test Scores”

Subprogram StartUp()

Set K = 1

Set NameBox.Text = Names[1]

End Subprogram

Top Label

Text = “Student name:”

Bottom Label

Text = “Test score:”

Top Text Box

Name = NameBox

Text = “”

Enabled = False

Bottom Text Box

Name = ScoreBox

Text = “”

Subprogram ScoreBox.Change()

Set EnterButton.Enabled = True

End Subprogram

Command Button

Name = EnterButton

Caption = “Enter”

Enabled = False

Subprogram EnterButton.Click()

Set Scores[K] = Val(ScoreBox.Text)

If K = N Then

End Program

Else

Set K = K + 1

Set NameBox.Text = Names[K]

Set ScoreBox.Text = “”

Set EnterButton.Enabled = False

End If

End Subprogram

Chapter 9

Problem 1

Main module

Declare Clubs, Diamonds, Hearts, Spades As Integer

Write “This program simulates 1000 deals from a deck of cards.”

Write “It counts the number of cards of each suit.”

Call Count Suits module

Call Display Results module

End Program

Count Suits module

Declare Card, K As Integer

Set Clubs = 0

Set Diamonds = 0

Set Hearts = 0

Set Spades = 0

For K = 1 Step 1 To 1000

Set Card = Random(52)

Select Case Of Card

Case 1-13:

Set Clubs = Clubs + 1

Case 14-26:

Set Diamonds = Diamonds + 1

Case 27-39:

Set Hearts = Hearts + 1

Case 40-52:

Set Spades = Spades + 1

End Case

End For

Display Results module

Write “Number of clubs: ”, Clubs

Write “Number of diamonds: ”, Diamonds

Write “Number of hearts: ”, Hearts

Write “Number of spades: ”, Spades

Problem 2

Main module

Declare First, Second, Third As Integer

Declare Name As Strings

Declare NameArray[1000] Of String

Write “This program randomly selects a first-, second-, and third-place”

Write “winner from the names stored in the file NAMES.”

Call Read Names module

Call Select Winners module

Call Display Winners module

End Program

Read Names module

Declare N, K As Integer

Open “NAMES” For Input As NameFile

Read NameFile, N

For K = 1 Step 1 To N

Read NameFile, NameArray[K]

End For

Close NameFile

Select Winners module

Set First = Random(N)

Repeat

Set Second = Random(N)

Until Second First

Repeat

Set Third = Random(N)

Until Third Second And Third First

Display Winners module

Write “First-prize winner: ”, NameArray[First]

Write “Second-prize winner: ”, NameArray[Second]

Write “Third-prize winner: ”, NameArray[Third]

Problem 3

Main module

Declare Names[100] Of Strings

Declare Scores1[100], Scores2[100] Of Reals

Declare Count As Integer

Write “This program sorts the records in the file GRADES in”

Write “alphabetical order by student name.”

Call Load File module

Call Sort module

Call Update File module

End Program

Load File module

Open “GRADES” For Input As GradeFile

Set Count = 0

While Not EOF(GradeFile)

Read GradeFile, Names[Count], Scores1[Count], Scores2[Count]

Set Count = Count + 1

End While

Close GradeFile

Sort module

Declare J, K, Index As Integer

Declare Min, Temp1 As String

Declare Temp2 As Real

For K = 0 Step 1 To Count - 2

Set Min = Names[K]

Set Index = K

For J = K + 1 Step 1 To Count - 1

If Names[J] < Min Then

Set Min = Names[J]

Set Index = J

End If

End For (J)

If K Index Then

Set Temp1 = Names[K]

Set Names[K] = Names[Index]

Set Names[Index] = Temp1

Set Temp2 = Scores1[K]

Set Scores1[K] = Scores1[Index]

Set Scroes1[Index] = Temp2

Set Temp2 = Scores2[K]

Set Scores2[K] = Scores2[Index]

Set Scroes2[Index] = Temp2

End If

End For (K)

Update File module

Declare K As Integer

Open “GRADES” For Output As GradeFile

For K = 0 Step 1 To Count - 1

Write GradeFile, Names[K], Scores1[K], Scores2[K]

End For

Close GradeFile

Problem 4

Main module

Declare Found, Count As Integer

Declare Names[100] Of Strings

Declare Scores1[100], Scores2[100] Of Reals

Declare Score1, Score2 As Real

Declare StudentName As String

Write “This program searches the file GRADES for a given name”

Write “and displays that student’s test scores.”

Call Load File module

Call Input Name module

Call Search module

Call Display Results module

End Program

Load File module

Open “GRADES” For Input As GradeFile

Set Count = 0

While NOT EOF(GradeFile)

Read GradeFile, Names[Count], Scores1[Count], Scores2[Count]

Set Count = Count + 1

End While

Close GradeFile

Input Name module

Write “Enter the student’s name.”

Input StudentName

Search module

Declare Low, High, Index As Integer

Declare Key As String

Set Key = StudentName

Set Low = 0

Set High = Count - 1

Set Index = Int(Count/2)

Set Found = 0

While (Found = 0) AND (Low Names[Index] Then

Set Low = Index + 1

Set Index = Int((High + Low)/2)

End If

If Key < Names[Index] Then

Set High = Index - 1

Set Index = Int((High + Low)/2)

End If

End While

Display Results module

If Found = 1 Then

Write StudentName

Write Score1

Write Score2

Else

Write StudentName, “ was not found in the GRADES file.”

End If

Problem 5

Declare K As Integer

Record Type StudentInfo

Name As String[25]

Score1 As Real

Score2 As Real

End Record

Declare Student As StudentInfo

Open “GRADES1” For Random As NewFile, Len = Length(Student)

Open “GRADES” For Input As GradeFile

Set K = 0

While NOT EOF(GradeFile)

Set K = K + 1

Read GradeFile, Student.Name, Student.Score1, Student.Score2

SeekPut NewFile, K, Student

End While

Close NewFile, GradeFile

End Program

Problem 6

Declare Last As Integer

Record Type StudentInfo

Name As String[25]

Score1 As Real

Score2 As Real

End Record

Declare Student As StudentInfo

Open “GRADES1” For Random As GradeFile, Len = Length(Student)

Call Add Student module

Call Change Score module

Call Switch Positions module

Close GradeFile

End Program

Add Student module

Write “Enter the new student’s name.”

Input Student.Name

Write “Enter the scores for Test 1, Test 2.”

Input Student.Score1, Student.Score2

Set Last = LOF(GradeFile) / Length(Student)

SeekPut GradeFile, Last +1, Student

Change Score module

Set Last = LOF(GradeFile) / Length(Student)

SeekGet GradeFile, Last, Student

Set Student.Score2 = 99

SeekPut GradeFile, Last, Student

Switch Positions module

Declare Student2 As StudentInfo

Set Last = LOF(GradeFile) / Length(Student)

SeekGet GradeFile, 1, Student

SeekGet GradeFile, Last, Student2

SeekPut GradeFile, Last, Student

SeekPut GradeFile, 1, Student2

Problem 8

Declare Count, Found, Index As Integer

Declare Names[100] Of Strings

Record Type StudentInfo

Name As String[25]

Score1 As Real

Score2 As Real

End Record

Declare Student As StudentInfo

Open “GRADES1” For Random As GradeFile, Len = Length(Student)

Call Load File module

Call Name Search module

Call Name Change module

Close GradeFile

End Program

Load File module

Open “GRADES2” For Input As IndexFile

Set Count = 0

While NOT EOF(IndexFile)

Read IndexFile, Names[Count]

Set Count = Count + 1

End While

Close IndexFile

Name Search module

Declare K As Integer

Set Found = 0

Set K = 0

While K < (Count – 1) AND Found = 0

Set K = K + 1

If Names[K] = “C. Fong” Then

Set Found = 1

Set Index = K

Set Names[K] = “C.L. Fong”

End If

End While

Name Change module

Declare K As Integer

If Found = 0 Then

Write “The name ‘C. Fong’ was not found.”

Else

SeekGet GradeFile, Index, Student

Set Student.Name = “C.L. Fong”

SeekPut GradeFile, Index, Student

Open “GRADES2” For Output As IndexFile

For K = 0 Step 1 To Count - 1

Write IndexFile, Names[K]

End For

End If

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download