UMAP MODULE478
'
MODULES
AND
MONOGRAPHS
IN
UNDERGRADUATE
MATHEMANCS
AND ITS
APPLICATIONS
F > F > F >
b
<
B
b
-
l
{
t r
Iterationand
Computer
Problem
Solving
E
Herbe(L. Dershem
o ' r r q ! o r !
' D ' > .
s
E.,
6o
s N a N 6 N
> @ > c D > @
6
x
x
x
> o
> o
>
' g t
E t g
e Z q
t t,t t
2 .
t,l t
Z
t,r
' 6 v G ' s
x
it x
stbat,chk!ot,deptot
I
:l.x
it
doptot,finbal
S , ! $ ' ! $ , 0
e
^
e
fr^
v^
e
\,
c . F . l s F l e t
BlrkhAuSer
Bostonlnc.
3A)Gr€enStreei
Cambridge,
MA01439
Computer
Science/Algorilhms
T
Desc?1:pti,an Sheet :
Inteno&tlar
Title:
-Author:
UMAPUnnt 478
SOI,VING
PROBLEM
ITEMTION AND COM?UTER
Herbert L. Dershen
Depatnent of conpute" Science
Hope College
Eol1and, Michigan 49423
: /39/81
R e v i e sS t a g e / D a t eM
Classification:
CoMPUTER
SCl/Ai,C0RITHltS
Prereouisite Skills:
a
Conpletion of UI{APU n i t 4 7 7 , r r c o n p u t e r P l o b l e n S o l v i n g . r r
Output Skills:
inprove alsorithns by enhancins then
l:--B-e-AEIt-to
and follo{
through (as a conPuter
2. Be able to read, intolpret,
would) argotithms that involve while, until, and vatiablecontrolled lteration.
3. Be able to describe snd apply the top-dom appraoch to algorithn' deslgn.
aornput-eif loEI etn soTvlns OJnit 4?7)
@ 198I EDc/Project UMAP
AII rights reserved.
ITODI'LESAND !,IONOG&AIES
IN UNDARGRADUATE
MATIIEMATICSAND ITS A}?LICATIONS ?ROJECT (UMAP)
The goal
of IIMAP 1s to develop,
through
a co@ntty
of users
and
nodrle8 in undelgladuate
mthedevelopers, a systen of instruetio@1
Mtlcs and its alpucations
that tuy be used to suPglesedt existing
coulses and flon Fhieh con?lete courses nay eventually be bu1lt.
lhe Project is guided by a Natlonal Advisoly loard of Ethemticians, sclentistE,
aDd educators.
UMAPis funded by a glant fron the
National Science Fouf,datiod to Education D€velopnedt Center, 1nc., a
publicly suploit,
nonproflt corlolation
engaged in educatlonal lesealch
ln the U.S. and abroad.
?&OJECT STAFI
Pj'sB !. Iinney
solonon A. Garfunkel
M. DeMat
lelicia
Barbala Kelczewskt
?aula M. santlllo
PloJect Dlrecto!
Execltive Dllecto!,
COMA?
Associate Dllecto!
coordlnator for Materlals Productlon
Asslstant to the Dtrectors
PloJect Secretary/Prodrctlon
Aseistant
Zachary Zevltas
UMAPAIVISORY BOARD
Steven J. Bram€
Llayron Clarkson
Donald A. La!6on
R. Duncan Luce
Frederlck !bste11er
George M, U111e!
Alnold A. Straesenlula
Nev Yolk Ufllve.Etty
Iexas Southern Unlvel8lty
SU\ry at Buffalo
Earvd?d Unlver€1ty
Italvard llnlvelslty
Nassau Comunlty College
U[lveralty
of Mtchlgan ?!esg
SUNYat Story Blook
ttsthenatlcal Aseoclatlon of An€rlca
Tht6 unlt waE fleld-test€d
and/or student leviesed in pr€Iindnary
forn by Halold Saker of Lltchtleld
Htgh Schooli and Alex G. lennett of
Blerelton lrlgh School and has been levtued on the basl6 of data recelved
fron these ettes.
The holect
would ltk€ to thank Douglas I. flate of the Untver6lty
of Texa8-lemlan lasln, O.leEBa, Texa8; Calol StokeB of Datrv1lle Alea
Ray Treadway of lennett college,
com$nlty college, Danvllle, Illlnols;
Creensboro, North CErollnai Calroll O, Wtlde of the Naval ?ostgraduate
Schoot, Monteley, Caltfo!f,tal
and ore anonyrcuE levleqte?, for thelr
revlevs, and all others lrho asel8led ln the productlon of thls unlt.
Thls Eaterlal l\'as prepsred vlth the partlal
6up?ort ot Natlonal
Sclerce Eoundatlon Clant No, SED80-07731, Reco@endatlons expre8sed are
those of the autho! ard do not necesEarlly ?eflect the v1€\r6 of the NSF
SOLVING
PROSL-EM
ITERATION AND COMPOTER
by
Herbert L. Dershern
Departrnent of ConPuter Sciellce
HoDe Colleqe
49423
H o ll a n d , ' M i c h i g a i
TABLE OF CONTENTS
2.
PROBI,EU
A I,IORTGAGE
3t
ITERATIIEIMPROVEI{EM
4.
ITEMTION
5.
I]IMTION
VARIABI,E-CONTROLLED
6,
APPROACH
TOP-DOIIN
7.
TO BXERCISBS
SOLUTIONS
8.
BXAM
MODEL
9.
SoLllIIoNs T0 li0DEL BXAl.l
1
I
INTRODUCTION
One of the najor advantages in using a conputer for
problen sotving is that a process can be explained to the
cornputer once and the conputer can repeat that process
a s ) n a n yt i n e s a s i s n e c e s s a r y t o s o l v e t h e p r o b l e n .
In
fact, without this conputers !,ould be of liniteil use
as problern solving ma€hinesbecause it generally takes
longer
to explain
a process to the conputer than to
carry it out by hand. Repeated execution of a single
set of instructions
on a sonputer is often ca11ed
ite?ati.an.
The term ttiteration" also refers to any singl e
executioD of a process that is carried out nore than
t h e s e n s e i n r h i c h t h e t e r n i s u s e d s h o u l d b e c l e a r fron
the context.
The nodule describes {ays in uhich you can use c o n puter iteration
effectively
in problenL solving and, i n
addition,
vrays in l,hich you can use t\,ro other forns o f
iteration in consttucting the algorithn.
T h e s e c o D d form
of iteration involves repeated tracing through of the
problen solying steps, inproving your algorithn oith each
iteration.
We call this process ite?atite inpral)enent in
aLgorithn design.
Each inprovenent of the algorithrn
add features to the previous verslon.
The third
forn
of iteration
in problen
sotving
night
is
found in aD approach to algorithn design celted tle
top-dolnn app!,aach. This approach for carring out step 4
of the problen solving process (see Unit 477) night best
be cal.led i.te?atire
inprovetnent in that
iteration,
!,eflnenent.
It
differs
fron iterative
the algorithn
is Dot changed at eech
but rather, nore detail is provided.
2. A MORTGAGE
PROBLEM
In order to i l l u s t l a t e
the iteration technique, we
s h a 1 1 s o t v e t h e following problen: given an arnount of
-1-
ratb, anal a nontha }'ear1y ilterest
after one nonth1y palnent, deternine the new princila1
for
th€ interest
1y laynrent has bee]I rnade and teterilire
one rnonth.
borro{eal principal,
The input for this algorithn consists of the
principal
at the beginllillg of the nonth, the yearly
interest rate exPressed as a decitnal r anil the smou,t of
the payment, The outPut will consist of all La1ues input
plus the part of the paynert xihich llli11 be useal to pay
the part of the peynent which uill
interest,
anal the nee principal
pay off the princiPsl,
the end of the nonth'
Algorithn
be used to
bslance at
1. Mortgege Peynent _ veasioll 1'
veriab les
Nano
rate
pay
intetest
pritlpaY
new
Desctiption
The principal balance et the
beginning of the nonth.
The yeerly rate of interest
expr€ssed as 4 decinal.
The ernountof the paynent.
The part of the palnent which
goes towald interest.
The part of the payment {hich
goes toward the Principal.
The new ptincipal balance at the
eflalbf the nonth.
-2-
pr1n, rate,
pay
p r i n p a y + p a y- i n t e r e s t
lntetest r prinpay
The interest is celculated by nultiplying
the prin_
cipi.e, prin, tines the interest rate divided by 12 be_
cause the giyen rate is fo! a year and the period used
is a nonth,
The value of prinpay is the arnount left
frorn the pafment pay after the interest is paid.
Finally,
n e t l |i s t h e p r i n c i p a l
l.
balance after
Choose sarnPlevalu€s for prin,
prinpay is paid.
Iate, and pay, and follow
through atgorithrn 4 as a
-3-
i
i
I
2.
Follor the steps in the f1o$chart tariguagealgolitlln berort
for sone sanple input values, The algorithro is one to balance
a checkbook.
Algg4llgi
Bararcins a checkbook
Variables
Nsne
Description
stbal
deptot
Ealsnce at the beginnldg of the noath.
Total ahount of atrl chgcks ,lrritten.
Total -a,no|fit of all deposits [ade during
flnbsl
Balence at the ond of, the oonth.
stbal , chktot , d6ptot
f inbel+stbel-chktot+d.ptot
stbal,chktot,
deptot,finbal,
3. ITERATIVE II{PROVEI{ENT
A l t h o L g h o u r n o r t g a g F p a y m F n ta l g o r i t h n I k i l l
I u n c t i o n p r o p e r l y r r f r i e r d l y v a l u e sa r e i n p u t . i t t r i 1 l
For exanple,
not respond in a suitable way to bad input.
consider the case in which the paynent is too snall to
c o v e r t h e i n t e r e s t f o r i h e n o n t h . S u p p o s ep r i n = 2 0 0 0 0 . ,
,ate = .09. rnd pav - .00. -f you fol lo\. t|rough the
steps of the algorithn
with these values as inpttt yo'r get
i n t e r e s t = 1 50 .
PrinPaY = '50'
= 20050.
new
0n the other hand, the paynent nay also be too large
In thls case, the paynent covers the interest and the
_r _here is stil1 sone extra left.
.
This is typical of the final paynent in a pay-back
schedule. For exanple, supposeprin = 60. ' rate = .09'
and pay = 100. Then, the calculalions \rould be
i n t e r e s t - 0 . 45 .
prinpay = 99.55.
= -39.55.
W e s h a 1 l u s e i t e r a t i v e i r n p r o v e r n e nt o c o r r e c t t h e s e
If the pay_
two rninor flaws in our original algorithn.
nent is too snal1, ve inforn the user and terninate the
progran; if it is loo large, lee pay off the loan and
notify
the user that he or she is entitled
to a refund,
These nodifications to Algorithin 1 are indicated in
Algorithn 2. The decislon box inctuded innediately after
t h e i n p u t b o x t e s t s f o r a p a y n e n t t o o s m a 1 1t o c o v e r t h e
l | l h e nt h i s i s t h e c a s e , r , v ep r o v i d e a m e s s a g e t o
interest.
This
the user and then iinnediatety halt the algorithn
actlon represents a policy of disallowing paynents lrhich
are inadequate to pay the interest.
5,
the interest pa),nert is calculated, we add
another decision box whicb tests for paynent gr:eater than
I n t h i s c a s e , l { . ec a l c u l a t e t h e n e l r p r i n the principal.
way and
in a different
cipat and anount paid on principal
p
r
i
n
c
i
p
al.
adjust prinpay to exactly pay lhe renaining
After
l , l l ea l s o i n c l u d e a n e s s a g e k h i c h n o t i f i e s
he or she will receive a refund.
Algorilhn
the user that
2 . M o r t g a g e p a y r n e n t- V e r s i o n 2 Variab1es
Nane
prln
Pay
interest
Description
The principal
balance at the
beginning of the r[onth.
The yearly rate of interest
expressed as a decinal.
The anount of the paynent.
prinpaY
The part of the paynent which
goes tolvard interest.
The part of the paynent which
goes tolrard the PrinciPAl
balance at the
The nel,l principal
overpay
end of the nonth.
The arnount of overpaynent f o r t h e
final paynent
L
ey<prin x ratel12
"Payrl]ent does
interest-prin x rate/12
3 y >i n t e r e s t + p r i n ?
prlnpay+prln
overpay+pay - prlnpay
,lnteres
pay+pay overpay
p r i n p a y + p a y -i n r e r e s t
r r Y o ua r e e n t i t t e d
to a refund of",
overpay
new.pri n- pr inpay
pli n, rate, pay, interest
prlnpay, ne\t
-7-
palmentrr
3 . F o l r o v t h r o u g h Algodthn 2 for the following
Test I
Test 2
Test 3
20000.
20000.
.72
.12
200.
.12
pav
250.
150.
400.
4. ITERATION
The next step in the inprovenen! of o u r n o r t g a g e
a l g o r i t h n w i l l b e t o g e n e r a t e a s c h e d u l e of payments by
repeatedly executing the algorithr
gi]/en a b o v e , T o
a s s i s t u s i n d o i n g t h i s , r , r eu s e t h e t h r e e f o r n s o f i t e r e tion that were introduced in Section 1.
We shall discuss two forns of iteration here, and
a third forn in the next section.
The first
fornLwill be
ca11ed the until itet,atian.
The iteration box which we
use to describe this
fol lowing diagran.
Until
iteration
construction
is indicated in the
e r n i n a ti o n T e s t
The body of the iteration
is actually
a subalgorithn
the ternination test is
which is to be repeated until
satisfied.
The body of the iteration is shownas a cloud
to indicate that this night be one or two boxes or a more
involved set of flowchart statenents,
In the latter case,
we will find it helpful to give the body a flol,chart of
its
own and include only its nane to the right of the
iteration box. fhe procedurefor doing that will be
8-
discussed 1ater.
The dasheil line frorn the body back to
the ternination
test indicates that this is an autonatic
branch in the atgorithr
and not one that neeals to be
explicitly
be e part
defined.
lfe can consider
of the iteration
box.
the ilashed tine
to
The second forn of the iteTatioD box is t}re hile
ite!,ation. This forn accornplishesexactly the sane action
as the until
iteriation but does it in a 1ogically opposite
vay.
Its generel forn is shown in the next diaqlan.
l----
- ---'
--- - -:-----r
I
hile
I teration
CofltinuatioD
Test
--J
The test is now ca11ed a continuation test because
the iteration is continued as long as the test is
satisfiod,
The continugtion test is elDays logical.ly
opposite to the ternination test; the trdo foans eae
introaluced because sone conputer lalguages naturally perforn the until iterations while others are designed for
r y h i1 e i t e r e t i o n s .
As an exanplo of the use of the iterations, colsider
the algorithrn for finding the greatest cotnnondlvisot.
Ile heve two ways of expressing this algorithn using the
.iteiarion boxesjust introducedAlgorithn 9. Given Uro nunbets, N and ltl, flnd their
gteatest comlon ilivisor using an iteration statonent.
Yariables
Nalre
n.c.';
N,trf
The two nunbers input to the
algorithn.
A counte! uhich i s t e s t e d f o r t h e
greates! connon tlivisor,
K
nr i ^n
-9-
i
a . U si n g u n t i l
iter:ation
START
K . m i n ( N ,M )
oes K divide
both N and M?
b . U si n g w h i l e i t c r a t l o n
("nin (N,M)
Does ( not
divide N or not
divide M?
N , M (,
Algorithns
3a and 3b are togically equivalent in
that they accomplish the sane task.
Note that the
condition in the iteration box of Algorithn 3b is the
logical negation of the one in the iteralion box of
Algorithn
3a. That is,
do not continue.
1
+
I
you terninate
precisely
1,'henyou
lle novr use these iteration
boxes to nake a final
iterative
inptovenent to our nortgage algorithn.
l/e
shal1 now have the algorithn continue to nake nonthty
payrnents until. the nortgage is paid off.
This algorithn
is given in our flowchart language in Algorithn 4.
Algorithn 4. Genetate the nonthly paynents necessary to
pay off a nortgage lllith initial
principal
pyin, yeatly
lnteres!
fate late, and rnonthly paynent pdy.
Veriables
Nane
tate
pey
interest
prinpey
newPrin
D e s c r i p ti o n
Principel anount,
Yearly rate of interest expressedas a decinal.
Anount of the monthly paynent.
Part of the nonthly peynent
n h i c h g o o s t o w a L di n t e r e s t .
P6rt of the nonthly peyrnent
lrhich goes to aril principal.
New principal after a peynent
has been made.
- 11-
prin, rate ,pay
nterest>pay
prinpay.prin?
newprin+0
prinpay+prin
pay+interest+pr in
"paynent does not
cover interest't
n c w p ri n + p r i n - p r i n p a y
Prln, rat e,pay, interes t ,
pr inpay,newprin
Prin+newprin
interes t+prin x rate/72
P l i n p a y + p a y- i n t e r e s t
prin,rate,pay
1n!eresr,prlnpay
r - - - - - - - - _ _ _ _-l
Much of this atgorithn looks farritiar fron
Algorithn 2.
Aftet the results for one nonth are prinleal
in an iterationr
that nonth,s. new prrncipat is then set
!o be the next nonth's beginning principal.
The irera_
tion finally terninates when the anount paid on
the
principal exceeds the principal balance.
Untike
Algorithn
2, we nolll call this a valiat parllent anal nake
it the right anount to pay off the debt exactly.
5 . V A RI A B L E . c O N T R o L L [IDT E M T T o A
I n t h e l a s t s e c t i o n r 1 r el e a r n e d a b o u t f o m s
of
rteratlon which repeated a subalgoritfun until
termination conalitions l/ere rnet or continuation
conilitions were
not.
Nou lre introduce a slightly
different
forn of
iteration.
This is iteration controlleil by a variabte.
The generel forrn of such an iteratron is
a
Initialize
control
variable
Modify
control
v ar i a b 1 e
Test contTol variable
ror a tefilination
conditi on
Success
It
should be noted that t h i s f o r n o f i t e r a t i o n i s
a
s p e c i a l c a s e o f the forn we s tudied in the p r e c e d i n g
S e c t i o n . T h i s iterat ion can b e s t a l e d i n t e r n s o f t h e
i n d i c a t e d i n the following diagrarn.
Previ ous
-13,
Initialize
Modify control
var iable
Test control
vari able for ternination
condition
-__---1
fa i lure
Body
The reason we give the variable controlled iteration
lts own form is that it is connonly used and is
directty
lmplementedin nost progranning languages.
The variable khich controls the iteration is
set to
sone initial
value at the beginning of the itcration.
It
is then nodified after each execution of the bo.ly
and the
rteration is terninated when the control variable
satis,
fies sone tern.ination condition.
In order to control the
iteration properly, the controt variabte shoulcl
not be
changed in the body. t,his Iorm of iteration
is particu_
lar1y useful
hen a process must be repeated a fixed
n u m b e ro f t i m e s . I n t h i s c a s e t h e c o n t r o l y a r i a b l e
is
used as a counter which in sone way keeps track of
the
number of tines the body has been executed.
Algorithn 5 provides an exanple of variabte_controtted
itcration.
In this case, !he variable count ls used to
count the nurrberof data values l,hich have been reacl
in.
It is initlatized
to 2 to indicare that the seconil
value is read during the execution of the boily. It
increnented by I each time, and when the increnrent make
s
count larger than N, thcn N values have been read,
the iteration is terninated.
l4
Alsorittun S.
the largest of N values
first
big+first
Test-n
count+2
count +1
c o u n ! > N?
Test -ne
t>big?
big+1sx1
Another nev box has been introduced
in this algorithrn.
This.is the triangular shaped procecture
box. The nane
inside such a box is the narde
of a procedure which is to be
executed at that point,
This type of box is used to
avoid
conplicated coDstructions in
the body of an iteration.
The flowchart for the proceilure
is then founal elsewh6re.
A procedure is actually a subalgorithn.
Instead of Ueginning
a n d e n d i n g r , l i t h S T A R Ta n a l S T O I
"
boxes, it, t"rrin"tio.;;*;;
are ENTERand EXIT. The ENTER
box of a procealure has a
pennant atlached to it which
gives rne nane by rhich
it is
called into action.
lihen u/earrive at the EXIT box
of the
procedure, re autona!icaIly
cease execution of the procedure
-15-
a n d b e g i n e x e c u t i o n i n t h e a l g o r i t h n w h i c h c a 1 1 e dt h e
procedure at the next sequential box after
Wewill use such a Procedure box as the body of a
loop when the body is longer than one or two boxes.
W e n o w c o n si d e r a n o t h e r e x a n p l e . s u p p o s e t h e r e a r e
30 students in a class and each student has a student
number and 10 qulz scores. The argorithm is to deternine
the sum of the quiz scores for each stLrdent. The
aI gorithn for solving this prob1em is presented as
A I g or i t h n 6 .
Here v,e have an iteration v,ithin an iteration.
This
is a construction that occurs frequently in algorithms.
Also note, in the Find-sum procedure, that srn needs to
be initialized to z-.ro before a sun is accunulated. If
t h i s i s n o t d o n e , a c u m u l a t i v e s u n o f a l l s t r . r d e n t s ,s c o r e s
dill be conputed. In Iact, tl.ere is no !uararree that
s u r ni s
zero at the very beginning of execution.
Atgorithn 6,
30 students.
F i n d t h e s u mo f l 0 q u i z s c o r e s f o r e a c h o f
V a r i a bI e s
u9ll9
stcnt
The counter for stJdents uhich gocs
The student number r,.ad for each
str.rdent.
Tie
c,,n
^{
ar.h
s+',,lanr
t <
^,, i ?
Thc counter fo- quizzes which goes
The quiz score read for each quiz
and student.
16
stcnt+1
stcnt +1
stcnt>30?
stnunber
qcnt+1
qcnt+
qcnt+l
surn-sufi+qscoTe
q c n t >1 0 ?
s!nuDber, sun
-17-
Modify algorlthn
6 to input the nunber of students and the
nunber of quiz scores for each student
5.
The follouing
for finding
boxes arc usod in a flo{chart
the tso largest
languge
algorithn
nunbers in a set of N nunbers,
Place tle boxes in the proper arangenent.
Variabl es
!e19
Description
N
The nunber of valDes in the set.
bigl
The biggest value read so far.
bi92
The next-to-biggest value read so far.
I
A counter used to count the nuinber of
START
STOP
.h<#>*
---t'-
-'\"-
GF .,i:-'t
alue>bigl?
bi C2+Value
bi g2-bigt
bigr+Value
6.
T h e f o l l o w i n g t J o x e sc a n b e u s e d t o c o n s r t u c t a n
argorithn for
conputlng the ncan of a set ol N nlnbers.
Arrange then in the
proler order.
Variabres
!e!g
Description
N
The nunber of values in the set,
I
T h e m e a no f t h e v a t u e s .
A counter used to count the nunbcr of vaiues
Sun
The su
STAIIT
l
;
"
of the values read_
1
I-I+1
I value I
STOP
t * * l
7.
Arrange the forlouing boxes to form an atgorithn
which finds atl
integers betaeen M and N lhich a r c e x r c t l y
divisibte by K.
Va!iabtes
!!I9
Dcsc!iption
(
Tlte loucr lihit ol the r.ngc of integers.
'Ihe
up!er limit of the ranec of integcls.
'Ihe
v a i u c w h o t e n u m b c r sa r e t o b e
Printcd.
A count.r used to test for ansuers which
I
goes rron ll to N_
19
START
v
STOP
I M,N,Kj
I+I+1
r;-l
divisible
'I'OP.DOWN
APPROACH
The top-down approacb for designing algorithms is a
technique that atlows the designer to handle a conplicated
a l g o r i t h n i n a s i n p l e w a y . T h e b a s i c a p p r o a c hi s t o
design the algorithn using po{erful boxes, then breaking
t h o s e b o x e s d o w n i n t o f l o w c h a r t s l , l i t h l e s s p o r , \ ' e r f u lb o x e s
and continuing that process until you are at a levet suitable for inrplenentation on a co)nputer,
In order to illustrate
this technique, we look at an
a l g o r i t h m f o r a r r a n g i n g N n u r n b e r si n n a t u r a l o r d e r .
Algorithm_7.
Read N nunbers and print
d e s c e n di n g o r d e r .
then in non-
Variabl es
Descrip!ion
N
The nunberof values in the
An array of N values
2A-
N,A(1),.,.,AiN)
P u t t h e n u n b e r sA ( l ) , . . . , A ( N )
j n n o n- d e s c e n d i n g o r d e r
A ( 1 1, . . . , A ( N l
This is obviously not the final solution to our problen
have not described the process in enough
since we stlll
The next step is to
detail for the conputer !o follow.
break the middle box itself down into an algorithn.
This is the beginning of iterative refinement.
A l g o r i t h n 8 . P u t t h e n u m b e r sA ( 1 ) , . . . , A ( N )
d e s c e n di n g o r d e r .
into non-
Var i abl es
Name
Descript ion
The nunber of values in the set.
An array of N values to be
k
A counter uhich goes Fron N Lo z.
The index of the largest value
frornA(1) t0 A(k).
2r-
This procedure, for k=N dohn to k=2, is to find thc
largesr of the first k vatues and ptace it at the kth
position. Thc first tinc, with k=N, we find the largcsr
in the entirc set and put it at the botton.
Thc next pass
through the itcration, with k=N-1, we ignorc A(Nl since
i t i s a l r e a d y c o r : r - a c t ,a n d p l a c e t h e t a r g e s t o f t h e f i r s t
N-1 values in the (N-1)st position. lvecontinuc the
processuntit all arc in order.
Next $e brcak down the box ,,find the targest
Al.g-9gt_!!-9. Find thc larg€sr or A(r),
it A( ax).
,A(k), call
Variables
I3,T!
k
large
j
qqs-!lupli_gll
An array of values_
Thc -unhe.ol vrlJes in rhe icL
Thc index of thc largest valLre from
Afl) to A(k)
T h c v a l u e o t A ( n a x) .
A J o u n r er h h i . I
22
pocs
ror 1 ro k.
S']'ART
LNTTR
AIi]>1arge-r
larse-A(j
FinallL
h . . c x p a n d t h e , , L x c h a r r g e . . _ "b o x t r o m A l g o r i t h , r
'this
requircs thrce (latj novcnents and one tcnrporary
locatron.
r\\ofitlrm
It
is given by thc toltoring atsorith
.
1 0 . L i x c h a n s cA ( m a x l a n d A { k ) .
Variablos
1l!u!9
!ci9]_i!.!r
9!
A r ar r a y o J \ , i l u e s .
'lhc in(lcxcs
ot the tuo valucs to
S'IART
t c m p .A ( l )
^(k)-^(nr.x)
h a v e , i n A l g o r i t h n s 7 - 10 , a I l o f t l l e s t e p s
t o c o m p l e t e t h c t a s k o f p l a c i n g t h e n L rr b e r s i n
combine these into one fl oHchart for Al!orithn
11.
-23-
CompleteAlgorithn
pr int
t o r e a d N n u i n b e r sa n d
then in
START
N , A ( i ) , . . . , A( N )
ENT!R
Order
A(11,...,A
I inJ - exch.rn ee tlj
ENl'ER
l arge+A(max)
(j ) >larile
t enp+A( k)
A( k ) . A ( m a x l
A { m a x) + t e m p
- 24-
large4A(j )
Algorithn
11 was designed by the top-down approach.
This neans that l,/e slart with the highest 1eve1 tasks and
proceed to break then doh.n into nore and rnore detailed
subtasks until finally we have an algorithn which is
detailed enough !o provide conptete instructions to
cornputers. In this way we have broken the original
p r o b l e n d o h a ri n t o t h r e e s i n p l e r p r o b l e m s .
In generalJ top-dol{n design is an approach whereby
problen is broken dol'n into several sinpler
a difficult
problens. Each of these sinpler problens nay atso be
broken doun into several sinpler ones, and so on until
aII of the problens to be sotved are within the grasp of
the problem solverThis iterative refinenent is a
very lnportant
8.
strategy ln conputer problen solving.
Uslng tho set of numbers5 , 3 , 9 , 6 , 2 , 7 f o l l o h J t h l o u g h A l g o r i t h m 1 l
as a conputer would.
7, SOLUTION
TS
O EXERCISES
result is prin = 20000.
r a t e= . 1 2
pay = 250.
'
interest = 200.
prinpay = 50.
n e w= 1 9 9 5 0 .
2S-
4.
C h a n g ef i r s t
flovchart
to:
srcnt+1
Changc i t erat ion box
qcn t - l
F i n d- s u n t o
START
big1,big2
ig2>bigl?
T e m p - bi g l
bigl+big2
big 2+Temp
I-l+l
alue>bie1
big2+bigl
b i g 1 + V aI u e
j gl ,big2
Value'hig2:
h ig 2+Value
---------J
I.I+l
mean+sun/N
I 're
Su'n-Sum+va
START
TI,N,K
IrI+l
divisibl
8.
1.
The follouing
algorithn
}IODELEXAM
reads a set of 50 nunbers
smallest nunber in the set.
prints
Modify the argorithm
not onll the smallest nunber, but also the
that nmber
occurs in the set.
k>50?
2.
algoritbn
years it
$1000 i.f it
iehich leads an anrouDtof noney and dete!'nines
u o u l d t a l e f o r that anrount to grow to over
a c c u n u l a t e s i n t e r e s t at the rate of 69 conpounded
Use each of the boxes below exactly once.
3 . Explain in your oun kords the toP-dorn a P p r o a c h t o a l g o r i t h m
design.
DiscDss uby it
is inPotant
-29
9.
SOLUT]ONSTO }IODEL EX4N,1
ll, count
anount+a$ountx 1.06