Vous êtes sur la page 1sur 25

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 e amples are given for each t!pe of IF statement and several solution algorithms that use the selection structure are developed. Encourage !our students to become familiar "ith the different forms of IF statements, especiall! nested IF statements, and their e pression in pseudocode. The case structure is introduced as a means of e pressing a linear nested IF statement in a simpler and more concise form. #ase is available in man! high level languages, and so is recommended as a useful construct to "rite in pseudocode.

Solutions to problems at the end of the chapter


Each problem re$uires the student to provide a solution that contains: % Defining diagram, a pseudocode algorithm, a des& chec& of the algorithm. Each algorithm re$uires onl! se$uence and selection control structures.

1 Design an algorithm that will receive two integer items from a terminal operator and display to the screen their sum difference product and !uotient" #ote that the !uotient calculation $first integer divided b% second integer& is onl% to be performed if the second integer does not e!ual 'ero" A
Input integer'( integer'*

Defining diagram
Processing )rompt for integers +et integers #alculate sum, difference, product, $uotient Displa! results Output sum difference product $uotient

B ( * , / 0 2

Solution algorithm #alculate'integer'values )rompt for t"o integers +et integer'(, integer'* sum - integer'( . integer'* difference - integer'( - integer'* product - integer'( 1 integer'* IF integer'* , 34 5ero T6E7 $uotient - integer'( 8 integer'* ELSE $uotient - 9 Displa! ;The sum is ;, sum Displa! ;The difference is ;, difference Displa! ;The product is ;, product IF $uotient 34 9 T6E7 Displa! ;The $uotient is ;, $uotient ELSE Displa! >The $uotient could not be determined? E7DIF E7D

: < = (9

16

C i

Desk checking Input data:


(irst data set integer'( integer'* *9 * Second data set (99 9

ii E pected results:
(irst data set sum difference product $uotient ** (< /9 (9 Second data set (99 (99 9 9

iii Des& chec& table:


Statement number (irst pass (, * , / 0 2 :, <, =, (9 Second pass (, * , / 0 2 :, <, =, (9 (99 9 (99 (99 9 displa! displa! displa! 9 message *9 * ** (< /9 displa! displa! displa! (9 displa! integer)1 integer)2 sum difference product !uotient

2 Design an algorithm that will read two numbers and an integer code from the screen" *he value of the integer code should be 1 2 3 or 4" +f the value of the code is 1 compute the sum of the two numbers" +f the code is 2 compute the difference $first minus second&" +f the code is 3 compute the product of the two numbers" +f the code is 4 and the second number is not 'ero compute the !uotient $first divided b% second&" +f the code is not e!ual to 1 2 3 or 4 display an error message" *he program is then to display the two numbers the integer code and the computed result to the screen" A
Input number_1 number_2 code

Defining diagram
Processing Prompt for two numbers, code Get two numbers, code Validate code Calculate result Display result Output result message

B ( * , /

Solution algorithm #alculate'ne"'value )rompt for t"o numbers and a one-digit integer code +et number'(, number'*, code Set message to blan& or Set message to > > #%SE @F code ( : result - number'( . number'* * : result - number'( - number'* , : result - number'( 1 number'* / : IF number'* 7@T - 5ero T6E7 result - number'( 8 number'* ELSE message - >The $uotient could not be determined? E7DIF other : message - >invalid integer code? E7D#%SE IF message - blan& T6E7 or IF message - > > Then Displa! >First integer: >, number'(, >Second integer: >, number'*, >Integer code: >, code, >#omputed result: >, result ELSE Displa! >First integer: >, number'(, >Second integer: >, number'*, >Integer code: >, code, message E7DIF
E7D

18

C i

Desk checking Input data:


First data set number_1 number_2 code 10 4 2 Second data set 20 !

ii Expected results:
First data set result message ! blan" Second data set in#alid integer code

iii Desk check table:


Statement number First pass 1, 2 $ 4 Second pass 1, 2 $ 4 20 ! blan" in#alid integer code display 10 4 2 blan" display display display ! display number_1 number_2 code result message

display

display

display

3 Design an algorithm that will prompt an operator for a student,s serial number and the student,s e-am score out of 1.." /our program is then to match the e-am score to a letter grade and print the grade to the screen" Calculate the letter grade as follows0 Exam score 1. and above 3.431 6.461 7.471 below 7. A
Input student_num score

Assigned grade 2 5 C D (

Defining diagram
Processing Prompt for student_num, score Get student_num, score Calculate grade Display grade Output grade

B ( * ,

Solution algorithm #alculate'student'grade )rompt for student serial number and e am score +et student'num, score IF score 4- =9 T6E7 grade - >%? ELSE IF score 4- ><9? T6E7 grade - >A? ELSE IF score 4- :9 T6E7 grade - >#? ELSE IF score 4- 29 T6E7 grade - >D? ELSE grade - >F? E7DIF E7DIF E7DIF E7DIF Displa! >%ssigned grade?, grade E7D

20

%lternatives to 7ested Ifs Bsing #%SE: #alculate'student'grade )rompt for student serial number and e am score +et student'num, score #%SE @F score 4 <=: grade - >%? 4 :=: grade - >A? 4 2=: grade - >#? 4 0=: grade - >D? other: grade - >F? E7D#%SE Displa! >%ssigned grade?, grade E7D

#alculate'student'grade )rompt for student serial number and e am score +et student'num, score #%SE @F score =9-(99: grade - >%? <9-<=: grade - >A? :9-:=: grade - >#? 29-2=: grade - >D? 9-0=: grade - >F? E7D#%SE Displa! >%ssigned grade?, grade E7D

C i

Desk checking Input data:


First data set student_num score 12$4 % Second data set 11111 0

ii Expected results:
First data set grade C Second data set &

iii Desk check table:


Statement number First pass 1, 2 $ 4 Second pass 1, 2 $ 4 11111 0 & display 12$4 % C display student_num score grade

22

4 Design an algorithm that will receive the weight of a parcel and determine the deliver% charge for that parcel" Charges are calculated as follows0 Parcel Weight (kg 82"5 9g 2"545 9g ;5 9g A
Input parcel_weig't

Cost per kg (! :3"5. per 9g :2"35 per 9g :2"45 per 9g

Defining diagram
Processing Prompt for parcel_weig't Get parcel_weig't Calculate deli#ery_c'arge Display deli#ery_c'arge Output deli#ery_c'arge

Solution algorithm

Note that the delivery charge or each parcel is deter!ined as a certain cost" per kilogram o parcel #eight$ #alculate'deliver!'charge )rompt for parcel "eightin &g C&ilogramsD +et parcel'"eight IF parcel'"eight 3 *.0 T6E7 deliver!'charge - E,.09 1 parcel'"eight ELSE IF parcel'"eight 3- 0 T6E7 deliver!'charge - E*.<0 1 parcel'"eight ELSE deliver!'charge - E*./0 1 parcel'"eight E7DIF E7DIF / Displa! >Deliver! charge for parcel is?, deliver!'charge E7D ( * ,

C i

Desk checking Input data:


First data set parcel_weig't 2 "g Second data set 4 "g

ii Expected results:
First data set deli#ery_c'arge (%)00 Second data set (11)40

iii Desk check table:


Statement number First pass 1, 2 $ 4 Second pass 1, 2 $ 4 4 (11)40 display 2 (%)00 display parcel_weight delivery_charge

2%

5 Design an algorithm that will prompt a terminal operator for the price of an article and a pricing code" /our 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 accompan%ing discount amount as follows0 Pricing code < ( * > ? Discount rate 5.= 4.= 33= 25= .=

+f the pricing code is ? then the words @#o discount, are to be printed on the screen" +f the pricing code is not < ( * > or ? then the words @+nvalid pricing code, are to be printed" A
Input price pricing_code

Defining diagram
Processing Prompt for price, pricing_code Get price, pricing_code Calculate discount_amount Calculate new_price Display price, discount_amount, new_price Output price discount_amount new_price *+o discount, *-n#alid pricing code,

B ( * , 0

Solution algorithm

#alculate'discounted'price )rompt for price and pricing code C6, F, T, F or GD +et price, pricing'code set message to blan& #%SE @F pricing'code >6? : discount'amount - price 1 9.0 >F? : discount'amount - price 1 9./ >T? : discount'amount - price 1 9.,, >F? : discount'amount - price 1 9.*0 >G? : message - >7o discount? other: message - >Invalid pricing code? E7D#%SE 2 IF message - blan& T6E7 ne"'price - price - discount'amount Displa! ?@riginal price: >, price, >Discount: >, discount'amount, >7e" price: >, ne"'price > ELSE Displa! >@riginal price: >, price, >)ricing code: >, pricing'code, message E7DIF E7D

C i

Desk checking Input data:


First data set price pricing_code (10)00 & Second data set (10)00 .

ii Expected results:
First data set price new_price message (10)00 (!)00 blan" Second data set (10)00 0 *-n#alid pricing code,

iii Desk check table:


Statement number First pass 1, 2 $, 4 ! display Second pass 1, 2 $, 4 ! (10)00 . 0 display display 0 blan" *-n#alid pricing code, display display (10)00 & 0 (4)00 0 (!)00 display blan" price pricing_code discount_amount new_price message

26

7 2n architect,s fee is calculated as a percentage of the cost of a building" *he fee is made up as follows0 3= of the first :5 ...".. of the cost of a building and 3= on the remainder if the remainder is less than or e!ual to :3. ...".. or 2A= on the remainder if the remainder is more than :3. ...".." Design an algorithm that will accept the cost of a building and calculate and display the architect,s fee" A
Input building_cost

Defining diagram
Processing Prompt for building_cost Get building_cost Calculate arc'itects_fee Display arc'itects_fee Output arc'itects_fee

B ( * , /

Solution algorithm

#alculate'architects'fee )rompt for building cost +et building'cost remainder - building'cost - E0,999.99 IF remainder 3- E<9,999.99 T6E7 architects'fee - CE0,999.99 1 <HD . Cremainder 1 ,HD ELSE architects'fee - CE0,999.99 1 <HD . Cremainder 1 *.0HD E7DIF 0 Displa! >%rchitect?s fee is?, architects'fee E7D

C i

Desk checking Input data:


First data set building_cost ( 0,000)00 Second data set (200,000)00

ii Expected results:
First data set arc'itects_fee (1,% 0)00 Second data set ( ,2% )00

iii Desk check table:


Statement number First pass 1, 2 $ 4 Second pass 1, 2 $ 4 (200,000)00 (1/ ,000)00 ( ,2% )00 display ( 0,000)00 (4 ,000)00 (1,% 0)00 display building_cost remainder architects_fee

28

6 2 home mortgage authorit% re!uires a deposit on a home loan according to the following schedule0 "oan ! less than :25 ... :25 ...4:41 111 :5. ...4:1.. ... Deposit 5= of loan value :125. B 1.= of loan over :25 ... :5... B 25= of loan over :5. ...

Coans in e-cess of :1.. ... are not allowed" Design an algorithm that will read a loan amount and compute and print the re!uired deposit" A
Input loan_amount

Defining diagram
Processing 0ead loan_amount Calculate deposit Print loan_amount, deposit Output loan_amount deposit

Solution algorithm

7ote that the #%SE structure cannot be used here as a range of values is involved. ( * , #ompute'loan'deposit Iead loan'amount Set message to blan& IF loan'amount 3 E*0,999 T6E7 deposit - loan'amount 1 9.90 ELSE IF loan'amount 3 E09,999 T6E7 remainder - loan'amount - E*0,999.99 deposit - E(,*09.99 . Cremainder 1 9.(D ELSE IF loan'amount 3- E(99,999 T6E7 remainder - loan'amount - E09,999.99 deposit - E0,999.99 . Cremainder 1 9.*0D ELSE )rint >Loans in e cess of E(99,999 are not allo"ed? E7DIF E7DIF E7DIF IF deposit 4 9 T6E7 )rint >Ie$uired deposit for loan amount >, loan'amount, >is?, deposit E7DIF E7D

C i

Desk checking Input data:


First data set loan_amount (20 000)00 Second data set (!0 000)00

ii Expected results:
First data set deposit (1 000)00 Second data set (% 00)00

iii Desk check table:


Statement number First pass 1 2 $ 4 Second pass 1 2 $ 4 (!0 000)00 0 (% 00)00 print blan" (10 000)00 (20 000)00 0 (1000)00 print blan" loan_amount deposit message remainder

print

print

&0

3 Design an algorithm that will receive a date in the format ddDmmD%%%% $for e-ample 21D.6D2..7& and validate it as follows0 i the month must be in the range 1412 and ii the da% must be in the range of 1431 and acceptable for the corresponding month" $Don,t forget a leap %ear chec9 for (ebruar%"& A
Input day mont' year

Defining diagram
Processing Prompt for day, mont', year Get day, mont', year Validate mont' Validate day Display message Output #alidation_message day mont' year

B ( * , /

Solution algorithm Jalidate'input'date )rompt for da!, month, !ear +et da!, month, !ear Set valid'date to true IF month 3 ( @I month 4 (* T6E7 Set valid'date to false Displa! >Invalid month?, month E7DIF IF da! 3 ( @I da! 4 ,( T6E7 Set valid'date to false Displa! >Invalid da!?, da! E7DIF IF valid'date T6E7 IF month - 9/, 92, 9=, @I (( T6E7 IF da! 4 ,9 T6E7 Set valid'date to false Displa! >Invalid da! for corresponding month?, da!, month E7DIF ELSE IF month - 9* T6E7 IF da! 4 *= T6E7 Set valid'date to false Displa! >Invalid da! for Februar!?, da!, month, !ear ELSE Divide !ear b! / into $uotient and remainder IF remainder 4 9 %7D da! 4 *< T6E7 Set valid'date to false Displa! >Invalid da! for Februar!?, da!, month, !ear E7DIF E7DIF E7DIF E7DIF E7DIF IF valid'date T6E7 Displa! >Date valid?, da!, >8?, month, >8?, !ear E7DIF

C i

Desk checking Input data:


First data set day1mont'1year 2/10212000 Second data set $211$1200!

ii Expected results:
First data set message *Date #alid, 2/10212000 Second data set *in#alid mont',, 1$ *in#alid day,, $2

iii Desk check table:


Statement number First pass 1, 2 $ 4 ! % Second pass 1, 2 $ 4 $2 1$ 200! true false false ! % *-n#alid mont', *-n#alid day, 2/ 02 2000 true day month year valid_date quotient remainder message

00 display display display

0 *Date #alid,

&2

1 *he ta- pa%able on ta-able incomes for emplo%ees in a certain countr% is set out in the following table0 #axa$le income (rom :1"..4:4471"11 (rom :4472"..4:16 313"11 (rom :16 314"..4:21 411"11 (rom :21 5.."..4:45 636"11 :45 633".. and over #ax paya$le #il #il plus 3. cents for each : in e-cess of :4472".. :4111".. plus 35 cents for each : in e-cess of :16 314".. :3757".. plus 47 cents for each : in e-cess of :21 5..".. :11 161".. plus 7. cents for each : in e-cess of :45 633"..

Design an algorithm that will read as input the ta-able income amount and calculate and print the ta- pa%able on that amount" A
Input ta2able_income

Defining diagram
Processing 0ead ta2able_income Calculate ta2_payable Print ta2_payable Output ta2_payable

Solution algorithm

7ote that the #%SE construct cannot be used here as a range of values is involved. ( * #alculate'ta 'pa!able Iead ta able'income IF ta able'income 3 E/,/2*.99 T6E7 ta 'pa!able - 9 ELSE IF ta able'income 3 E(:,<=/.99 T6E7 remainder - ta able'income - E/,/2*.99 ta 'pa!able - remainder 1 9.,9 ELSE IF ta able'income 3 E*=,099.99 T6E7 remainder - ta able'income - E(:,<=/.99 ta 'pa!able - E/,((=.99 . Cremainder 1 9.,0D ELSE IF ta able'income 3 E/0,:<<.99 T6E7 remainder - ta able'income - E*=,099.99 ta 'pa!able - E<,202.99 . Cremainder 1 9./2D ELSE remainder - ta able'income - E/0,:<<.99 ta 'pa!able - E((,(:=.99 . Cremainder 1 9.29D E7DIF E7DIF E7DIF E7DIF )rint >Ta pa!able is?, ta 'pa!able E7D

C i

Desk checking Input data:


First data set ta2able_income (4,000)00 Second data set (24,000)000

ii Expected results:
First data set ta2_payable (0)00 Second data set (!,2 !)10

iii Desk check table:


Statement number First pass 1 2 $ Second pass 1 2 $ (24,000)00 (!,10!)00 (!2 !)10 print (4,000)00 (0)00 print ta able_income remainder ta _payable

&%

1. 2 transaction record on a sales commission file contains the retail price of an item sold a transaction code that indicates the sales commission categor% to which an item can belong and the emplo%ee number of the person who sold the item" *he transaction code can contain the values S E or C which indicate that the percentage commission will be 5= 6= or 1.= respectivel%" 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 emplo%ee number" A
Input transaction record retail_price trans_code emp_number

Defining diagram
Processing 0ead transaction record Calculate commission Print transaction details Output retail_price commission emp_number

Solution algorithm

7ote that the #%SE construct can be used here. In the solution algorithm, if the transaction code is not S, K, or L, then a message "ill print and the commission "ill be set to 5ero. ( * )rocess'transaction'record Iead retail'price, trans'code, emp'number #%SE @F trans'code >S?: commission - retail'price 1 9.90 >K?: commission - retail'price 1 9.9: >L?: commission - retail'price 1 9.( other : Displa! >Invalid transaction code?, trans'code commission - 5ero E7D#%SE )rint >Ietail price: >, retail'price, >#ommission: >, commission, >Emplo!ee 7umber: >, emp'number E7D

C i

Desk checking Input data:


First data set retail_price trans_code emp_number ( 0)00 . 12$4 Second data set (!0)00 3 $4 !%

ii Expected results:
First data set commission (2) 0 Second data set (!)00

iii Desk check table:


Statement number First pass 1 2 $ Second pass 1 2 $ (!0)00 3 $4 !% (!)00 print ( 0)00 . 12$4 (2) 0 print retail_price trans_code emp_number commission

&6

Sample e-amination !uestions


1 % combined IF statement is one that contains multiple conditions, each connected "ith the logical operators %7D or @I. E plain, "ith the use of an e ample, the difference bet"een the t"o logical operators. 2 7ame the t"o t!pes of nested IF statements, and e plain the difference bet"een them. 3 Lhat is a Aoolean variableM 4 The #%SE structure e tends the selection control structure from a choice bet"een t"o values to a choice bet"een multiple values. 6o" else can !ou e press a choice bet"een multiple values in pseudocodeM 5 CTrue or FalseD % linear nested IF statement can be replaced "ith a #%SE statement. 7 The algorithm belo" uses a #%SE statement. E press the same algorithm using a linear nested IF statement: #%SE of option (: %-%.( *: A-A.( ,: #-#.( /: D-D.( E7D#%SE

2nswers to sample e-amination !uestions 1 % combined IF statement that uses the logical operator %7D, "ill re$uire both conditions to be true, for the IF clause be true. For e ample, the pseudocode: IF gender - male %7D age 3 *9 T6E7 increment counter E7DIF "ill onl! increment the counter if both conditions are true % combined IF statement that uses the logical operator @I, "ill re$uire Nust one of the conditions to be true, for the IF clause to be true. For e ample, the pseudocode: IF gender - male @I age 3 *9 T6E7 increment counter E7DIF "ill increment the counter if one or both conditions are true. 2 The t"o t!pes of nested IF statements are the linear nested IF and the non-linear nested IF. % linear nested IF has ELSE statements that immediatel! follo" the IF conditions to "hich the! correspond. For e ample: IF record'code - ( T6E7 add ( to counter'( ELSE IF record'code - * T6E7 add ( to counter'* ELSE add ( to counter', E7DIF E7DIF % non-linear nested IF has ELSE statements that ma! be separated from the IF statements to "hich the! correspond. For e ample: IF gender - male T6E7 IF age 4 *9 T6E7 add ( to !oung'male ELSE add ( to old'male E7DIF ELSE add ( to female E7DIF 3 % Aoolean variable is one that can contain Nust one of t"o values, true or false. 4 The #%SE construct can also be e pressed as a linear nested IF statement. 5 True. % linear nested IF statement can be replaced "ith a #%SE statement, if the values are simple values, not a range of values.

&8

7 The follo"ing linear nested IF statement "ill operate the same as the #%SE statement. IF option - ( T6E7 add ( to % ELSE IF option - * T6E7 add ( to A ELSE IF option - , T6E7 add ( to # ELSE IF option - / T6E7 add ( to D E7DIF E7DIF E7DIF E7DIF