29
Chapter 4 Selection control structures Objectives To elaborate on the uses of simple selection, multiple selection and nested selection in algorithms To introduce the case construct in pseudocode To develop algorithms using variations of the selection control structure Overview This chapter covers the selection control structure in detail: 1 the simple IF statement, 2 the null ELSE statement, 3 the combined IF statement, 4 the linear nested IF statement, 5 the non-linear nested IF statement. Descriptions and pseudocode examples are given for each type of IF statement and several solution algorithms that use the selection structure are developed. Encourage your students to become familiar with the different forms of IF statements, especially nested IF statements, and their expression in pseudocode. The case structure is introduced as a means of expressing a linear nested IF statement in a simpler and more concise form. Case is available in many high level languages, and so is recommended as a useful construct to write in pseudocode. Solutions to problems at the end of the chapter Each problem requires the student to provide a solution that contains: A Defining diagram, a pseudocode algorithm, a desk check of the algorithm. Each algorithm requires only sequence and selection control structures.

Problems and Solutions - C4 (1)

Embed Size (px)

Citation preview

Page 1: Problems and Solutions - C4 (1)

Chapter 4Selection control structures

Objectives To elaborate on the uses of simple selection, multiple selection and nested selection in

algorithms To introduce the case construct in pseudocode To develop algorithms using variations of the selection control structure

OverviewThis chapter covers the selection control structure in detail:1 the simple IF statement,2 the null ELSE statement,3 the combined IF statement,4 the linear nested IF statement,5 the non-linear nested IF statement.

Descriptions and pseudocode examples are given for each type of IF statement and several solution algorithms that use the selection structure are developed. Encourage your students to become familiar with the different forms of IF statements, especially nested IF statements, and their expression in pseudocode.

The case structure is introduced as a means of expressing a linear nested IF statement in a simpler and more concise form. Case is available in many high level languages, and so is recommended as a useful construct to write in pseudocode.

Solutions to problems at the end of the chapterEach problem requires the student to provide a solution that contains: A Defining diagram, a pseudocode algorithm, a desk check of the algorithm.

Each algorithm requires only sequence and selection control structures.

Page 2: Problems and Solutions - C4 (1)

1 Design an algorithm that will receive two integer items from a terminal operator, and display to the screen their sum, difference, product and quotient. Note that the quotient calculation (first integer divided by second integer) is only to be performed if the second integer does not equal zero.

A Defining diagram

Input Processing Output

integer_1 Prompt for integers suminteger_2 Get integers difference

Calculate sum, difference, product, quotient productDisplay results quotient

B Solution algorithm

Calculate_integer_values1 Prompt for two integers2 Get integer_1, integer_23 sum = integer_1 + integer_24 difference = integer_1 - integer_25 product = integer_1 * integer_26 IF integer_2 , <> zero THEN quotient = integer_1 / integer_2 ELSE quotient = 07 Display 'The sum is ', sum8 Display 'The difference is ', difference9 Display 'The product is ', product10 IF quotient <> 0 THEN Display 'The quotient is ', quotient ELSE Display ‘The quotient could not be determined’ ENDIF END

16

Page 3: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

integer_1 20 100integer_2 2 0

ii Expected results:

First data set Second data set

sum 22 100difference 18 100product 40 0quotient 10 0

iii Desk check table:

Statement number

integer_1 integer_2 sum difference product quotient

First pass

1, 2 20 23 224 185 406 107, 8, 9, 10 display display display display

Second pass

1, 2 100 03 1004 1005 06 07, 8, 9, 10 display display display message

Page 4: Problems and Solutions - C4 (1)

2 Design an algorithm that will read two numbers and an integer code from the screen. The value of the integer code should be 1, 2, 3 or 4. If the value of the code is 1, compute the sum of the two numbers. If the code is 2, compute the difference (first minus second). If the code is 3, compute the product of the two numbers. If the code is 4, and the second number is not zero, compute the quotient (first divided by second). If the code is not equal to 1, 2, 3 or 4, display an error message. The program is then to display the two numbers, the integer code and the computed result to the screen.

A Defining diagram

Input Processing Output

number_1 Prompt for two numbers, code resultnumber_2 Get two numbers, code messagecode Validate code

Calculate resultDisplay result

B Solution algorithm

Calculate_new_value1 Prompt for two numbers and a one-digit integer code2 Get number_1, number_2, code3 Set message to blank or Set message to ‘ ‘4 CASE OF code 1 : result = number_1 + number_2 2 : result = number_1 - number_2 3 : result = number_1 * number_2 4 : IF number_2 NOT = zero THEN result = number_1 / number_2

ELSE message = ‘The quotient could not be determined’

ENDIF other : message = ‘invalid integer code’ ENDCASE5 IF message = blank THEN or IF message = ‘ ‘ Then

Display ‘First integer: ‘, number_1, ‘Second integer: ‘, number_2, ‘Integer code: ‘, code, ‘Computed result: ‘, result

ELSE Display ‘First integer: ‘, number_1, ‘Second integer: ‘, number_2, ‘Integer code: ‘, code,

message ENDIF

END

18

Page 5: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

number_1 10 20number_2 4 5code 2 6

ii Expected results:

First data set Second data set

result 6message blank invalid integer code

iii Desk check table:

Statement number

number_1 number_2 code result message

First pass

1, 2 10 4 23 blank4 65 display display display display

Second pass

1, 2 20 5 63 blank4 invalid integer

code5 display display display display

Page 6: Problems and Solutions - C4 (1)

3 Design an algorithm that will prompt an operator for a student’s serial number and the student’s exam score out of 100. Your program is then to match the exam score to a letter grade and print the grade to the screen. Calculate the letter grade as follows:

Exam score Assigned grade

90 and above A80–89 B70–79 C60–69 D

below 60 F

A Defining diagram

Input Processing Output

student_num Prompt for student_num, score gradescore Get student_num, score

Calculate gradeDisplay grade

B Solution algorithm

Calculate_student_grade1 Prompt for student serial number and exam score2 Get student_num, score3 IF score >= 90 THEN grade = ‘A’ ELSE IF score >= ‘80’ THEN grade = ‘B’ ELSE IF score >= 70 THEN grade = ‘C’ ELSE IF score >= 60 THEN grade = ‘D’ ELSE grade = ‘F’ ENDIF ENDIF ENDIF ENDIF4 Display ‘Assigned grade’, grade END

20

Page 7: Problems and Solutions - C4 (1)

Alternatives to Nested Ifs Using CASE:

Calculate_student_grade Prompt for student serial number and exam score Get student_num, score CASE OF score > 89: grade = ‘A’ > 79: grade = ‘B’ > 69: grade = ‘C’ > 59: grade = ‘D’ other: grade = ‘F’ ENDCASE Display ‘Assigned grade’, gradeEND

Calculate_student_grade Prompt for student serial number and exam score Get student_num, score CASE OF score 90-100: grade = ‘A’ 80-89: grade = ‘B’ 70-79: grade = ‘C’ 60-69: grade = ‘D’ 0-59: grade = ‘F’ ENDCASE Display ‘Assigned grade’, gradeEND

Page 8: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

student_num 12345 11111score 75 50

ii Expected results:

First data set Second data set

grade C F

iii Desk check table:

Statement number

student_num score grade

First pass

1, 2 12345 753 C4 display

Second pass

1, 2 11111 503 F4 display

22

Page 9: Problems and Solutions - C4 (1)

4 Design an algorithm that will receive the weight of a parcel and determine the delivery charge for that parcel. Charges are calculated as follows:

Parcel Weight (kg) Cost per kg ($)

<2.5 kg $3.50 per kg2.5–5 kg $2.85 per kg

>5 kg $2.45 per kg

A Defining diagram

Input Processing Output

parcel_weight Prompt for parcel_weight delivery_chargeGet parcel_weightCalculate delivery_chargeDisplay delivery_charge

B Solution algorithm

Note that the delivery charge for each parcel is determined as a certain cost, per kilogram of parcel weight.

Calculate_delivery_charge1 Prompt for parcel weightin kg (kilograms)2 Get parcel_weight3 IF parcel_weight < 2.5 THEN delivery_charge = $3.50 * parcel_weight ELSE IF parcel_weight <= 5 THEN delivery_charge = $2.85 * parcel_weight ELSE delivery_charge = $2.45 * parcel_weight ENDIF ENDIF4 Display ‘Delivery charge for parcel is’, delivery_charge END

Page 10: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

parcel_weight 2 kg 4 kg

ii Expected results:

First data set Second data set

delivery_charge $7.00 $11.40

iii Desk check table:

Statement number

parcel_weight delivery_charge

First pass

1, 2 23 $7.004 display

Second pass

1, 2 43 $11.404 display

24

Page 11: Problems and Solutions - C4 (1)

5 Design an algorithm that will prompt a terminal operator for the price of an article and a pricing code. Your program is then to calculate a discount rate according to the pricing code and print to the screen the original price of the article, the discount amount and the new discounted price. Calculate the pricing code and accompanying discount amount as follows:

Pricing code Discount rate

H 50%F 40%T 33%Q 25%Z 0%

If the pricing code is Z, then the words ‘No discount’ are to be printed on the screen. If the pricing code is not H, F, T, Q or Z then the words ‘Invalid pricing code’ are to be printed.

A Defining diagram

Input Processing Output

price Prompt for price, pricing_code pricepricing_code Get price, pricing_code discount_amount

Calculate discount_amount new_priceCalculate new_price ‘No discount’Display price, discount_amount, new_price ‘Invalid pricing code’

B Solution algorithm

Calculate_discounted_price1 Prompt for price and pricing code (H, F, T, Q or Z)2 Get price, pricing_code3 set message to blank5 CASE OF pricing_code ‘H’ : discount_amount = price * 0.5 ‘F’ : discount_amount = price * 0.4 ‘T’ : discount_amount = price * 0.33 ‘Q’ : discount_amount = price * 0.25 ‘Z’ : message = ‘No discount’ other: message = ‘Invalid pricing code’ ENDCASE6 IF message = blank THEN new_price = price - discount_amount Display ’Original price: ‘, price, ‘Discount: ‘, discount_amount, ‘New price: ‘, new_price ‘ ELSE Display ‘Original price: ‘, price, ‘Pricing code: ‘, pricing_code, message ENDIF END

Page 12: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

price $10.00 $10.00pricing_code F S

ii Expected results:

First data set Second data set

price $10.00 $10.00new_price $6.00 0message blank ‘Invalid pricing code’

iii Desk check table:

Statement number

price pricing_code discount_amount new_price message

First pass

1, 2 $10.00 F3, 4 0 0 blank5 $4.006 $6.00

display display display

Second pass

1, 2 $10.00 S3, 4 0 0 blank5 ‘Invalid

pricing code’6 display display display

26

Page 13: Problems and Solutions - C4 (1)

6 An architect’s fee is calculated as a percentage of the cost of a building. The fee is made up as follows:

8% of the first $5,000.00 of the cost of a building and3% on the remainder if the remainder is less than or equal to $80,000.00 or2½% on the remainder if the remainder is more than $80,000.00.

Design an algorithm that will accept the cost of a building and calculate and display the architect’s fee.

A Defining diagram

Input Processing Output

building_cost Prompt for building_cost architects_feeGet building_costCalculate architects_feeDisplay architects_fee

B Solution algorithm

Calculate_architects_fee1 Prompt for building cost2 Get building_cost3 remainder = building_cost - $5,000.004 IF remainder <= $80,000.00 THEN architects_fee = ($5,000.00 * 8%) + (remainder * 3%) ELSE architects_fee = ($5,000.00 * 8%) + (remainder * 2.5%) ENDIF5 Display ‘Architect’s fee is’, architects_fee END

Page 14: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

building_cost $50,000.00 $200,000.00

ii Expected results:

First data set Second data set

architects_fee $1,750.00 $5,275.00

iii Desk check table:

Statement number

building_cost remainder architects_fee

First pass

1, 2 $50,000.003 $45,000.004 $1,750.005 display

Second pass

1, 2 $200,000.003 $195,000.004 $5,275.005 display

28

Page 15: Problems and Solutions - C4 (1)

7 A home mortgage authority requires a deposit on a home loan according to the following schedule:

Loan $ Deposit

less than $25 000 5% of loan value$25 000–$49 999 $1250 + 10% of loan over $25 000$50 000–$100 000 $5000 + 25% of loan over $50 000

Loans in excess of $100 000 are not allowed. Design an algorithm that will read a loan amount and compute and print the required deposit.

A Defining diagram

Input Processing Output

loan_amount Read loan_amount loan_amountCalculate deposit depositPrint loan_amount, deposit

B Solution algorithm

Note that the CASE structure cannot be used here as a range of values is involved.

Compute_loan_deposit1 Read loan_amount2 Set message to blank3 IF loan_amount < $25,000 THEN deposit = loan_amount * 0.05 ELSE IF loan_amount < $50,000 THEN remainder = loan_amount - $25,000.00 deposit = $1,250.00 + (remainder * 0.1) ELSE IF loan_amount <= $100,000 THEN remainder = loan_amount - $50,000.00 deposit = $5,000.00 + (remainder * 0.25) ELSE Print ‘Loans in excess of $100,000 are not allowed’ ENDIF ENDIF ENDIF4 IF deposit > 0 THEN Print ‘Required deposit for loan amount ‘, loan_amount, ‘is’, deposit ENDIF END

Page 16: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

loan_amount $20 000.00 $60 000.00

ii Expected results:

First data set Second data set

deposit $1 000.00 $7 500.00

iii Desk check table:

Statement number

loan_amount deposit message remainder

First pass

1 $20 000.002 0 blank3 $1000.004 print print

Second pass

1 $60 000.002 0 blank3 $7500.00 $10 000.004 print print

30

Page 17: Problems and Solutions - C4 (1)

8 Design an algorithm that will receive a date in the format dd/mm/yyyy (for example, 21/07/2006) and validate it as follows:

i the month must be in the range 1–12, andii the day must be in the range of 1–31 and acceptable for the corresponding month.

(Don’t forget a leap year check for February.)

A Defining diagram

Input Processing Output

day Prompt for day, month, year validation_messagemonth Get day, month, year dayyear Validate month month

Validate day yearDisplay message

B Solution algorithm

Validate_input_date1 Prompt for day, month, year2 Get day, month, year3 Set valid_date to true4 IF month < 1 OR month > 12 THEN Set valid_date to false Display ‘Invalid month’, month ENDIF5 IF day < 1 OR day > 31 THEN Set valid_date to false Display ‘Invalid day’, day ENDIF6 IF valid_date THEN IF month = 04, 06, 09, OR 11 THEN IF day > 30 THEN Set valid_date to false Display ‘Invalid day for corresponding month’, day, month ENDIF ELSE IF month = 02 THEN IF day > 29 THEN Set valid_date to false Display ‘Invalid day for February’, day, month, year ELSE Divide year by 4 into quotient and remainder IF remainder > 0 AND day > 28 THEN Set valid_date to false Display ‘Invalid day for February’, day, month, year ENDIF ENDIF ENDIF ENDIF ENDIF7 IF valid_date THEN Display ‘Date valid’, day, ‘/’, month, ‘/’, year ENDIF

Page 18: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

day/month/year 29/02/2000 32/13/2006

ii Expected results:

First data set Second data set

message ‘Date valid’ 29/02/2000 ‘invalid month’, 13‘invalid day’, 32

iii Desk check table:

Statement number

day month year valid_date quotient remainder message

First pass

1, 2 29 02 20003 true456 500 07 display display display ‘Date

valid’

Second pass

1, 2 32 13 20063 true4 false ‘Invalid

month’5 false ‘Invalid

day’67

32

Page 19: Problems and Solutions - C4 (1)

9 The tax payable on taxable incomes for employees in a certain country is set out in the following table:

Taxable income Tax payable

From $1.00–$4461.99 NilFrom $4462.00–$17 893.99 Nil plus 30 cents for each $

in excess of $4462.00From $17 894.00–$29 499.99 $4119.00 plus 35 cents for each $

in excess of $17 894.00From $29 500.00–$45 787.99 $8656.00 plus 46 cents for each $

in excess of $29 500.00 $45 788.00 and over $11 179.00 plus 60 cents for each $

in excess of $45 788.00

Design an algorithm that will read as input the taxable income amount and calculate and print the tax payable on that amount.

A Defining diagram

Input Processing Output

taxable_income Read taxable_income tax_payableCalculate tax_payablePrint tax_payable

B Solution algorithm

Note that the CASE construct cannot be used here as a range of values is involved.

Calculate_tax_payable1 Read taxable_income2 IF taxable_income < $4,462.00 THEN tax_payable = 0 ELSE IF taxable_income < $17,894.00 THEN remainder = taxable_income - $4,462.00 tax_payable = remainder * 0.30 ELSE IF taxable_income < $29,500.00 THEN remainder = taxable_income - $17,894.00 tax_payable = $4,119.00 + (remainder * 0.35) ELSE IF taxable_income < $45,788.00 THEN remainder = taxable_income - $29,500.00 tax_payable = $8,656.00 + (remainder * 0.46) ELSE remainder = taxable_income - $45,788.00 tax_payable = $11,179.00 + (remainder * 0.60) ENDIF ENDIF ENDIF ENDIF3 Print ‘Tax payable is’, tax_payable END

Page 20: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

taxable_income $4,000.00 $24,000.000

ii Expected results:

First data set Second data set

tax_payable $0.00 $6,256.10

iii Desk check table:

Statement number taxable_income remainder tax_payable

First pass

1 $4,000.002 $0.003 print

Second pass

1 $24,000.002 $6,106.00 $6256.103 print

34

Page 21: Problems and Solutions - C4 (1)

10 A transaction record on a sales commission file contains the retail price of an item sold, a transaction code that indicates the sales commission category to which an item can belong, and the employee number of the person who sold the item. The transaction code can contain the values S, M or L, which indicate that the percentage commission will be 5%, 7% or 10% respectively. Construct an algorithm that will read a record on the file, calculate the commission owing for that record, and print the retail price, commission and employee number.

A Defining diagram

Input Processing Output

transaction record Read transaction record retail_price retail_price Calculate commission commission trans_code Print transaction details emp_number emp_number

B Solution algorithm

Note that the CASE construct can be used here. In the solution algorithm, if the transaction code is not S, M, or L, then a message will print and the commission will be set to zero.

Process_transaction_record1 Read retail_price, trans_code, emp_number2 CASE OF trans_code ‘S’: commission = retail_price * 0.05 ‘M’: commission = retail_price * 0.07 ‘L’: commission = retail_price * 0.1 other : Display ‘Invalid transaction code’, trans_code commission = zero ENDCASE3 Print ‘Retail price: ‘, retail_price, ‘Commission: ‘, commission,

‘Employee Number: ‘, emp_number END

Page 22: Problems and Solutions - C4 (1)

C Desk checking

i Input data:

First data set Second data set

retail_price $50.00 $60.00trans_code S Lemp_number 12345 34567

ii Expected results:

First data set Second data set

commission $2.50 $6.00

iii Desk check table:

Statement number retail_price trans_code emp_number commission

First pass

1 $50.00 S 123452 $2.503 print

Second pass

1 $60.00 L 345672 $6.003 print

36

Page 23: Problems and Solutions - C4 (1)

Sample examination questions1 A combined IF statement is one that contains multiple conditions, each connected with the

logical operators AND or OR. Explain, with the use of an example, the difference between the two logical operators.

2 Name the two types of nested IF statements, and explain the difference between them.3 What is a Boolean variable?4 The CASE structure extends the selection control structure from a choice between two values

to a choice between multiple values. How else can you express a choice between multiple values in pseudocode?

5 (True or False) A linear nested IF statement can be replaced with a CASE statement.6 The algorithm below uses a CASE statement. Express the same algorithm using a linear

nested IF statement:CASE of option 1: A = A + 1 2: B = B + 1 3: C = C + 1 4: D = D + 1ENDCASE

Page 24: Problems and Solutions - C4 (1)

Answers to sample examination questions

1 A combined IF statement that uses the logical operator AND, will require both conditions to be true, for the IF clause be true. For example, the pseudocode:IF gender = male AND age < 20 THEN increment counterENDIFwill only increment the counter if both conditions are trueA combined IF statement that uses the logical operator OR, will require just one of the conditions to be true, for the IF clause to be true. For example, the pseudocode:IF gender = male OR age < 20 THEN increment counterENDIFwill increment the counter if one or both conditions are true.

2 The two types of nested IF statements are the linear nested IF and the non-linear nested IF. A linear nested IF has ELSE statements that immediately follow the IF conditions to which they correspond. For example:IF record_code = 1 THEN add 1 to counter_1ELSE IF record_code = 2 THEN add 1 to counter_2 ELSE add 1 to counter_3 ENDIFENDIFA non-linear nested IF has ELSE statements that may be separated from the IF statements to which they correspond. For example:IF gender = male THEN IF age > 20 THEN add 1 to young_male ELSE add 1 to old_male ENDIFELSE add 1 to femaleENDIF

3 A Boolean variable is one that can contain just one of two values, true or false.4 The CASE construct can also be expressed as a linear nested IF statement.5 True. A linear nested IF statement can be replaced with a CASE statement, if the values are

simple values, not a range of values.

38

Page 25: Problems and Solutions - C4 (1)

6 The following linear nested IF statement will operate the same as the CASE statement.IF option = 1 THEN add 1 to AELSE IF option = 2 THEN add 1 to B ELSE IF option = 3 THEN add 1 to C ELSE IF option = 4 THEN add 1 to D ENDIF ENDIF ENDIFENDIF