Field r Apple imoleGamePlaYing meTaxes.Sil Compu(ing p,gr-spralCqmP{ins COVERSTORY T^ -'IhJomp."nen"iu" a xB a s e. . . . . . . . . . . in"ome tax databaseoogrdmTlf::,':::: i;iil:iiiHil;il;'.1.r"i"r. ::;;;;r;tu;;;;;;"panns S and p'r"r'aairv vea-r-end ur'o uur vourta\ rormsb PautHotl'da'' ' DeductioD Prosramming ' 'l"ii'.-,ilt"n, Your ComPuler for a Tax smau a into hobb) ho' conueningv"ur compurer 't "*' * bill bvMa* Battersht 34 ' Machines The . "rh; IncrcdibleTime how'T1l:1'1"::::::T"^' !onsur!dnt ;;i;;. ; ;;s..ent .shos' oincebutonthe 3E How to Add Graphsto Your CornputerOutPut ^-,c comprehenquickanalysis,and graPhs canprovide tor ' "ia, "lJal tun"'ion sraphs rn'g "af,r;tl" t'odu'e l#I,i"",i'.ii.lii'i,iili,jlu-*'ir'i 44 iulir"t" ;ffiffi "- "tttl* v.* #;Jrril;i; noiinit'"u""ount"t'' InglasKsa ortime-consum sy r"lingouerroutine \uchaspranmatteA imponant rormore ""f.itiii":ta"tt ;;;;i;;;;-il.ii.;-.c-urire bvKi ottdH utt"n nincanddecision-making i '.i**r-n' by R.Tickell andproiecrs -a p**nranons or tor schoolpaper{ LAUNOHINGPAI) ^V::I,; #1T1.'#ililliti;l Cr:::.,n";n:."1 :*ru:::''1. ;;;;;*"'* *i'* r'i 58 l""'"#'i'T:lli!."'ll;lli,":.T'i'fl :-["':,'il for you!,y RrynondT Viuone creations DIGGINGIN in BASIC Programming Recursive .' " " '16 "'::;f#llTi::ilT'11iff frepenoire [i::ffi li::',$:#.1,*r:;:,tlll;: to trnr varuabre vour add a ;d vou'l ;;;;;;;6;d;^-tby Heftert L Dershcm ON THE LIGHTDRSIDE ' -A SirnDleGamePlayitrgFi€ld . ' retsvouusea r00Kr00 forgames primarirv fiil:"'"JJ,,ii"i JJGed 50 pi"vr"gr"ii *'tr'.t'"q"iring lotsof memor]orbookteeping DEPARTMENTS FEEDBACK . . . , . . . ' . . .3 RANDOMACCESS... .9 COMPUTERBRIDGE . .53 FIRMWAREFACTS . ..56 COMPUTERCTIESS.. .62 . .. .. . ..74 BOOKSHELF UP .76 COMING WHAT'S ADINDEX...........111 hy L.D. StMder Co o Copyright 1919,Benvill PublislingCo+, a Molgan_GBnpian aPRrL1s7e PersonalComPuiing I Recursive Prograrnmin€ inBASIC BY HERBERT L. DERSHEM Recursive algoithms areanathemrto the personal compul ingprogrammer. Theirfeputationsuffersfrom the belief that fecursion requires a large,powerfulcomputeranda fancylanguage. programming Peopleconsiderrecursive so complicated that you needa degree in computerscience to understand it. But no onewith thst muchexperience would bolherwith recursion. lt is,so the myth go€s,highlyinefficient,wastefulofr€sources andonly a loy for acad€mics to playwith. But the mythsarcfalse.Recunioncanbe a valuabl€ tool on a personal computerusingBASICandshouldbe in every programmels reperioire. Anythingis recursive if it is definedin termsofitself. In programming, a recursive subroutine is onethat callson it, sell Peoplecommonlyconfuserecursion wilh iterution; both canbe usedto solvethe sameproblem, But recucionanditerationarecleaflydistinct.A proc€. dureis it€rativeifthe sameprocess is performed many times.A procedure is recursive ifin themiddleof its execution ii cals uponitseli A fecursive procedure beginsanothei ex€cutionofitselfbeforeihe originalis finished.Such a procedure hasmorethanoneexecutionin pfogress ai a giventime;aniteraiiveprocedure neverhasmorcthanon€. NoreverylanguaBe implemenration pern'irs recuision. In BASIC,recunionis only possible ifit is permissible to calla subroutine frornitselfandstil retainthe abilityof the originalexecutionto returnto the properpoint.The folloMngprogram canle\l yourBAslc fo- recursion capability. 10 Rttt TEst !0R Iu! tBrlrrY o! TItl aasrc t0 plt!oR{ tEcotslolr. 20 [=1 l0 T=0 40 GOSUB 100 50 Ir I<>2*[-1 Tgtll 1?0 8 0 G O T O3 0 16 PenonalComputing aPRrLreTe 100 I=I+1 I1O IF I<[ r ?0 iElltr! THlN 'I30 1 1 0 e os u B 1 0 0 140 Ir I>2*n- 1 TflElr 't70 1 5 0 I = r +1 1 60 tEl0Rll 1't0 t!IllT tr[ct t!c0RsIv!(it{-1itrTIttEs. tr 180 !!rD Everycall ofsubroutine100increments I by one.The Nth callwill resultin I beingsetto N anda returnwithout a recursive call.Thiswill retun to eachof theprevious tevels,incrementing I by oneon eachreturn,On the final return,I shouldequal2*N-I if thepfocess wascarriedout correctly.Thus,ifthe aboveprograrn runsfor a givenvalue ol N,lhe\,elsion of BASIC usedwill allowN.I recursrve calls.ManyvelsioasofBASIChavevirtuallyno limit on th€ numberof suchcallspossible. Ifthe BASICis not recursive to the appropriate levelfor somevalueofN, ir will usually respondwith som€iype of diagnostic message ratherthan arriveal statement170. Ifyour computer's BASICallowsrecursive subroutines, you now facethe problemoflvritingthem.Here\ a general outlineofa recunivesubroutine in BASIC. L Ifthe firsi call,initializethestackpointer2. If teminationcondition,computeresultidecremeni stackpointerireturn. 3. Do computation. 4. Saven€cessary valuesin stack. 5. Incrementstackpoinier. 6. Recursively callthissub.ouiine. 7, Restorcsaved valuesfrom the stack, 8. Do any remaining computation. 9. Decrement stackpointer. 10.Reiurn. \vhenyou re.uajvelycaila sJbrouline,rom itself.Ihe variablesin the calledexecutiondestroythe variablesof the samenamein rhe callingexecurion.To preserveihe original valuesof thesevariables,savein a dirnensionedvanable you needlo recalllater.Sup(caleda stack)thosevanables three variables(xJ andz) it has subroutine ;ose vour whenil retumslroma re.ursive wirhesto savetor recall call. The format of the stackdimensioned riable A lbr wouldbe: thissubroutine A(l) X from execuiionI A (2) Y from execution 1 A (3) Z from executionI A (4) X from execution2 A (s) Y irom execution2 A(6) Z from execution2 To keeptrackof tlle positionin the stackwhelethe its values,a pointeris used'This currenlexecuiionsaves by oointeris incremeflted the requirednunber,in the cal is made,and atoveexanple3, everytime a.ecursive by lhesameamounlon ea!hIelurn' emenleo de('the shoss above procedure ourlined recursive seneral genetal sleps3 In lhe subroudne. call rn onlyon; tecursive timesbefolethe returnat several to 8 maybe repeated 9 and 10. steDs andseehow lhesesleps sr.rbrouline Lt\ takea recursive is the standaldfitst example The factorial areimplemented. a it alsorepresents because unfortunately, ofrec;nion Droblemwherercculsionrsnot thebestwayro oblaina ir i( thernosrfamiliarandsimpleslof ;olulion.HoweveI, sowhy bleaktradiiion? all examples. Thecommondefiniiionof N facrorial(Nl) is iterative: 0 ! =I N:=N- (N-l) (N-2}" *2alforN=I.2 definitionofN faclorial: But thereis alsoa Iecursive 0 ! =I N ' = N * O { - 1 )fro rN = l , 2 , . . . ln thiscas;the factoriaiis definedin termsofitself,but clausewhichoccursat 0!. Therecuaive with oneescape form of a subloutineto computeN! isl 960 iE[ tnrs st!Ro0Tr[! coltPoTEsN FACIORITI, RECI'!SI!!I,Y AND 970 rlt Srolls lll! RlsolT rI !. tltE lrRsT cAL!, rs To 990' 980 !!tt tErs lRocRltt rs rt{ RlDro sBlcK l,!v!L r BASrC990 s:l 1 O 0 OI F n = 0 l D B l l l = 1 : s - s - 1 : R I T S R N l 0 t 0 c ( S )= n t 020 s=s+t 1 O 3 O{ = I - ' ! l c c s ! ! 1 0 0 0 1 0 4 0N = A{ s ) 1050 l=N*r 1050 s=s-1 1070!rruiN to stepI in 990 colresponds In thisprogram,statement l000corre_ given Slarement eal[er. gened algorilhm rhe ro step2, -here rhe terninalioncondilionis N=0 soon-ds bv I in thisproThestackis increnentedanddecremenied whena lccursive N. is raved va rable. onlyone srambecaus€ correspond plogram this in No compulations ;aI is nade. 1010to and slatements general atgorithm, of the step 3 to lo(Iepr4ro l0 reipecrivelv l07Ocorespond of lhefactorial ileraiveversion of cou$;,lhesimpra' subroutineexecutesmuch faster: Sl]ElOoTIllE 910 8eI IIIRATII' I O C O I T P O I E BN I A C T O i I I L axD sro!! r1 rll P. 980 tlr 990 REr{lllls PRocrat rs tn r Blsrc. RADrO SqlC!( tt{El 1000r=1 1010 IF !<=1 IllEll llToRl{ 1020 ror I=2 10 N ?=FI 1030 't040 lrxT r 1050 llTolll isurecomputa' ofrecursion exampie Anothercommon TheNthnum_ ofnumberssequence tionofihe Fibonacci F(N),is definedin termsof berin the Fibonaccisequence, its two predecessors. F(0) = 0 F(1) = 1 F ( N ) =F ( N - l ) +F ( N - 2f)o r N = 2 , 3 , . . . Your BASICrcrsionof thisalgorithmis: 9-70!!r 50BRO0lrN! 990 cALCoLlllS 1llE Ntl FrBOnrccr NotlBlR o 8 0 ! ! i ! ! c D l s r v E l Y a { D D E T 0 nS IT Tr{F. n.S. LIVFL T BrSlC. 990 s=1 1 0 0 0 I F ( F = 0 )+ ( ! = 1 ) Tg!I !=I: S=5-2: REtlt !N 1 0 1 0 I ( s )= ! 020 s=s+2 0 3 0 n = I - 1 : G O S ! B1 0 0 0 0tr0 lr=a(sl 0 5 0 A ( s + 1 )= ! 050 0 7 0 tl=N-2: G0sltB 1000 080 !-r ts+1, +! 0 9 0 S-S-2 1 1 0 0 RtT0t t! therearetwo stackenlriesfor eachcall ln thisexample. level.TheStil entryin A is the valueof N for that calllev€I, andthe (St1)st is thevalueof F(N-1) Again.asin the caseof thefactorial.iterationgivesa mo!€€fficientsolutionto thisproblem 970 !Et! SttBiolTr[E 1000 crlcol^Tls tli i !Tll !tBoNlccr llltltB!l IND lET0RliSrr 980 lEt rt!!altrrlY 990 !!tl It rs llRrTTEllr! llDro I BASIC. stilcK l!t!! 000 I=1rP=0 0t0 FOi I=t TO n_l 020 0=r 030 !=!+? 0q0 t[ F' P:Q 050 Nlrt r 0 RlTotI 015 couldbe of recursion Althoughyour first two ex3mples is the desiredlechnique betterdoneiterativelv.recursion for many pfobiemsbecauseit greallv simplili€sihe solution p'ogram dnorilhm -Now ,nd ia i.pt".'.nlarronin a BASIC t.o suchp oblemslhe filsris rhe fower consrder of Hanoi,a well-knownproblemwhichis nicelytreatedln ofthree pegs, a recu$ivemanner.Thisproblemconsists all ol differD disks, whichwe will calipegs1,2 and3, and the pegs. Initiallv on the stacked ent radius,whichcanbe size with of decreasing peg 1 in older on thsksarestacked rhelarqestdiskon the bottom.Theproblemis to movethe disksfrom peg1 to peg2 with the restriclionth't disks mustbe movedoneat a time from onepegto another,ano L\at no disk;ay everbe stackedon top ofa sn'.llerdisk' Computing l7 aPRrL1e7e Personal Therecuri\esolution generajizes lheproblenio move ^ u osis lron pegI- ro pegF by movingrhetop D.l disks on pegE ro rhe{jtrd pe8.movingLheoneremaining djskon pegF to pe€f. andrher movingalJof Lhediskson tle thi,d pegio pegf.J1;s reduces rheproblemof movingD disksro lru moves.ol D.I di.ks.TherecJrsive aiCoriLhmlor moving the top D disksfrom pegE to pegF is: I If D=l . movetop diskf(omE to F. rcturn 2 l.er c oe rhenlmber oi rhepegwtuchis nor E or F. r. Kecu.rrlety ca lrr procedure lo moverheropD-l disksfron E ro c. 4. Movethediskon E io F. 5. R€cursively caltthisprocedure to moveth€ top I}1 disksfron C to F. 6. Return In orrrimplenrentation,store thenumberof dlskson peg -. I in A(I), for I=1,2,3. Thevaluesthatneealto be sav€d whena recursive callis madearet, F andD. Our BAslc rersinnof thrsalSorithmis rhen: rhelisr relariveto theeventua] positionofX. Th<!jocessrs repeat€d unlilI andJ cross. Al !}lalpoinllhered,raEe. menta completed. Figure1 showsan exampieofthi; I->12 t2 t2 12 12 75 I >15 3 I 3 b0 ool>o0t.\0 44 13 13 13 13 I >13 x >46 X->46 X-N6X->46 JX_>46IJX 44 44 44I >44 60 94 94 94 94 94 49 49 49 49 49 95 95J >95 95 95 J >3J->3 75 75 75 FrgureI Theproeramto accornplish thisprocess is: 960 9?0 !!d TotlR o! Itlltol suBRo0TlNE TO I'OVBTIE tOP D DISCS 980 RE! rro !!c ! To PEG g I I T T E I I ! I R . S . ! E ! E I . r. I BASIC. 990 r 0 0 0r ! D = 1 I t ! l = l ( 8 , - t : r ( p , - A ( F , + 1 . P F r N t n f i 0 v En , Ei t r T O , i p : c O t O 1 0 i 90 | 0 1 0 G= 6 - { E + t l 1 0 2 0 a ( s )= t : A ( s + l ) = p : t ( s + 2 ) = D 1 0 3 0 s = s + 3 : D = D -1 : F = c 1 0 4 0c 0 s 0 s 1 0 0 0 1 0 5 0 r = a( s l : r = t ( s l 1 ) : D = r ( S + 2 1 1 0 6 0 r ( E -l r ( l t - 1 . r ( r l : r ( r , + 1 : PRr!T (Il0V!ir. E. trTOri F 1 0 7 0 s = s + 3 : D = ! - 1 : ! ' = 6 -l ! + ! I 1 0 8 0c 0 s 0 ! 1 0 0 0 1 0 9 0s = s - 3 1 1 0 0R l T 0 t l l a finatusefulapplication of lecursion. _ Now consider Lhequrcksort atgorirhm.oneof lhemosrefficjent and wjd€Iyusedsortingalgoritlms,is veryeasilyprogrammed Suplosew€havevaluesstorcdin A(L), . . ., AGD and vr'ewishto placethevaluesin ascending orderin ne same storage locations_ Thebasicquicksortalgorithmchooses somearbitraryvaluefiom thislisr,sayX=A(K),laenre" arranges tlrevaluesso thai ali valuessmallerthanX are locatedbefor€ii in the lisr andall valueslarserthanX are locatedafterit. ThenX will be at its correctsorted position in rheiisr.sayA{l). Thecamealgorirhmis fien recu;sivety appliedwrrhL andl-l in placeof L ard H, andrhenaqain appliedusingI+l and H. whenthe algorithmiqcaltedwirh L=8, wesrmpryreturn. Theonly part ofthe algorithmthai needssomeaddi X is in its properrosiiionandall othervalueslie or Lne propersideofX. Keepingtwo pointers,IandJ, accomplhlEs ihis process.I startsby pointing at the lirsr position in thelist, L. J pointsto H. ThenpointerI is moveddown thelist until a valueis encountered whichh no smalier than X. This valueof A(I) shouldthereforeLiebetowX in the list. Next pointer J is movedup the list until it encounlersa nunberno large,thanX. Tharnurnberis eychanged wi$ A(I), andboih arerhenin rtreproperparrof l8 Personal Computing apRrL 1e7e 12 1.2 J J A l3r_>lJ >46X >46 60I_X0 94 e4 49 49 95 95 75 75 FE! QOICT(SORT_SOBIOUIIN' TO REtnnaic! A(!) THF0 A(fl) SO THlt c- 7 0 ? E [ l l t v r l o B s < = x L I i i E r o n E x I N D T L I V A I U E S> = X l T E A I T E R . 980 iE!{ x Is Atrr{T{(L+0,/2}. INITTAL caLL T0 990 sorTs r(ll _a(N). 990 1 0 0 0I r l > = i c o t o 1 1 0 0 10 1 0 [=INT ( (I{fl) /2) : r=a (|l] : r=L: JEB 1 0 2 0M ( I ' < t r THEII=I+1: coTo l02o 1 0 3 0Il l(.1) >I Afi!N it=it-t: cOTo 1030 1 0 r r 0r F I < = J r s B r = r { r , : A( r t = A( i r t: r ( J l = 1 :r = r + 1 : , t = J -I 1 0 5 0 IF I<=,t THIN GoTO1020 1 0 6 0A ( s ) = I : l l s + 1 ) = f l 1 0 7 0E = J r5 = S + 2 : c o s 0 B1 0 0 0 i 080 I=r (Sl: B:t (s+11 1 0 9 0l = r : s = s + 2 rc o s o ! 1 0 0 0 1 1 0 0S : S - 2 : i ! 1 0 ! N In thisprogmm,star€ment lOO0teslsfof termination. Stat€nentsl0l0 to 1050partjtionthe list into lhosevalues smallerthanX andthoselargerthanX. Therwo recursive calhJollosstaremenr t050.only Lwovalues,I andH, are savedduringihe recunivecall, Anrllustration ofan execuljon of lhequicksort algo. rithm isgrvenin Fi8ure2. Theo'rginat tirrotrennumbers is roundon Ihe far lefi. ThecirclednumbelsareLhevaiues usedfor X. andthenumber-parrs in recranqtes arctne vdlues oi L andH usedto parntionrhelisl.\oie rharwe beginwith L:l, H=10.X=46.X is tien placedby partitioningin !}lelfrh position.Nexrrheoroce(srsca edlor X=J, L-1. H=4andX-49,L=6.H=tO.Theproces\ conlrnues In thisway unlil all vaiuesarecorrecdyso ed. tr