Pascal Tutorial 过程式编程语言.docx
PascalTutorial-IntroIntroductionIFYOUKNOWNOTHINGABOUTPASCA1.AssumingthatyouknownothingatallaboutPascal,andinfact,thatyoumayknownothingaboutprogrammingingeneral,wewillbegintostudyPascal.IfyouarealreadysomewhatfamiliarwithprogrammingandespeciallyPascal,youW川probablywanttoskipveryquicklythroughthefirstfewchapters.Youshouldatleastskimthesechapters,andyoushouldreadtheremainderofthisintroduction.Afewcommentsareinordertogetusstartedintherightdirection.ThesampleprogramsincludedwiththistutorialaredesignedtoteachyouthebasicsofPascalandtheydonotincludeanycleverortrickycode.Nearlyalloftheprogramsarereallyquitedumbasfarasbeingusefulprograms,butallwillteachoneormoreprinciplesofPascal.Ihaveseenonetutorialthatincludeda12pageprogramasthefirstexample.Infacttherewereonly2exampleprogramsintheentiretutorial,anditwasimpossibletogleantheessentialsofprogrammingfromthatsystem.Forthisreason,Iwillcompletelybypassanylongprogramsuntiltheveryendofthistutorial.Inorderto川UStratefundamentalconceptsusedinPascalprogramming,allprogramswillbeveryshortandconciseuntilwereachthelastchapter.1.ARGERPASCA1.PROGRAMSChapter16hassomeratherlargeprogramstoillustratetoyouhowtowritealargeprogram.ItwouldbeadisservicetoyoutoshowyoualloftheconstructsofPascalandnotshowyouhowtoputthemtogetherinameaningfulwaytobuildalargeprogram.AftercompletingallofthefundamentalsofPascal,itwillthenbeveryeasyforyoutousethetoolslearnedtobuildaslargeaprogramasyoudesireorrequireforyournextprogrammingproject.AnotherproblemIhavenoticedinexampleprogramsistheuseofonewordforalldefinitions.Forexample,asortprogramisstoredinafilecalledSORT,theprogramisnamedSort,andvariouspartsoftheprogramarereferredtoasSortl1Sort2,etc.Thiscanbeconfusingsinceyouhavenoideaiftheprogramnamemustbethesameasthefilename,orifanyoftheothernameswerechosentobethesamebecauseofsomeobscurerulenotclearlydocumented.Forthisreason,theexampleprogramsusecompletelyarbitrarynameswheneverthechoiceofanameaddsnothingtothereadabilityorclarityofaprogram.Asan川UStrationofthistthefirstprogramisnamedPuppy_Dog.ThisaddsnothingtotheunderstandingoftheprogrambutdoesillustratethattheprogramnamemeansnothingtothePascalcompilerconcerningwhattheprogramdoes.DuetothefundamentaldesignofthePascallanguage,certainwordsare"reserved"andcanonlybeusedfortheirdefinedpurposes.ThesearelistedinyorTURBOPascalreferencemanual.Allofthesampleprogramsinthistutorialarewrittenwiththereservedwordsinalllower-caseletters,andtheuservariablesinlowercasewiththefirstlettercapitalizedsincethisisbecominganacceptedindustrystandard.Don'tworryaboutwhatreservedwordsareyet,theywillbecompletelydefinedlater.Inthistutorial,allreservedwords,typenames,variablenames,andprocedureandfunctionnameswillbelistedinboldfacetypewithinthetextasanaidtothestudent.whatIsacompiler?TherearetwomethodsusedtorunanycomputerprogramthatiswritteninareadableformofEnglish.Thefirstmethodistouseaninterpreter.Aninterpreterisaprogramthatlooksateachlineofthe"English"program,decideswhatthe"English"onthatlinemeans,anddoeswhatitsaystodo.Ifoneofthelinesisexecutedrepeatedly,itmustbescannedandanalyzedeachtime,greatlyslowingdownthesolutionoftheproblemathand.Acompiler,ontheotherhand,isaprogramthatlooksateach"English"statementonetimeandconvertsitintoacodethatthecomputerunderstandsdirectly.Whenthecompiledprogramisactuallyrun,thecomputerdoesnothavetofigureoutwhateachstatementmeans,itisalreadyinaformthatthecomputercanrundirectly,resultinginmuchfasterexecutionoftheprogram.ThistutorialiswrittenespeciallyforBorlandInternational'sTURBOPascalcompilersversion5.0through7.0.Theseareveryhighqualitycompilersthatcandonearlyanythingyouwillaskthemtodosincetheyaresoflexible.TheoriginalintentofthistutorialwastowriteitinsuchawaythatitwouldbecompletelygenericandusablewithanygoodPascalcompiler.TheprogrammersatBorlandincludedagreatmanynonstandardaidsforthePascallanguageandresultedinaverygoodproductthathasdominatedthemarketformicrocomputers.TocompletelyomitalloftheextensionswoulddothoseofyouwiththeBorlandcompilerarealdisservice,andtoincludetheextensionswouldnotallowothercompilerstobeusedeffectivelywiththistutorial.ThedecisionwasmadetousetheBorlandextensionswhichmaymakethetutorialdifficulttousewithothercompilers.IfyouhaveaneedtousePascalwithsomeothercompiler,TURBOPascalissoinexpensivethatitwouldbeawisedecisiontopurchaseacopysolelyforthepurposeoflearningthePascalprogramminglanguage,thenmovingtotheothercompileronaminicomputeroramainframeusingtheaccumulatedknowledgetoveryquicklylearntheextensionsprovidedbythatparticularcompiler.Atanyrate,thistutorialwillnotteachyoueverythingyouwilleverneedtoknowaboutPascal.Itwill,however,teachyouthefundamentalsandtheadvancedfeaturesofPascal,butofevenmoreimportanceistheknowledgeofPascalterminologyneededtoprogressonyourownintomoreadvancedtopicsofPascalandprogrammingingeneral.Youwillfindthatexperiencewillbeyourbestteacher.WHICHVERSIONOFTURBOPASCA1.?SomeoftheexampleprogramswillnotworkwithsomeoftheearlierversionsofTURBOPascal.Thisisprimarilyduetothefactthatobjectorientedprogrammingcapabilitieswereaddedtoversion5.5,andimprovedoninlaterversions.Mostoftheexampleprogramswillworkwithanyversionhowever.ItshouldbepointedoutthateachsuccessiveversionofTURBOPascalhasbeenanimprovementoverthepreviousversionsinceadditionalcapabilitieshavebeenadded,andeachnewonecompilesalittlefasterandresultsinsmallerbutfasterexecutablecodethanthepreviousversion.AnyoftheversionsofTURBOPascalcanbeusedtolearntoprograminPascal,sowhicheverversionyouhaveonhandwillbeadequate.1.ater,whenyoubecomemoreversedinprogrammingtechniques,youmaywishtoupgradetotheabsolutelatestversion.EAR1.YVERSIONSOFTURBOPASCA1.MostofthefileswillcompileproperlywithTURBOPascalversions2.0through4.0.Nowarningwillbegivenaboutwhichfileswillnotcompilewiththeseversionssincetheyhavebeensupersededforsolong.Ifyouarestillusingoneoftheearlierversions,itwouldbegoodforyoutopurchaseanewerversionbecauseoftheflexibility.WHATABOUTTURBOPASCA1.VERSION5.5&NEWER?Chapters14and15ofthistutorialarewrittenespeciallyforTURBOPascalversion5.5andnewertodiscusstheuseofobjectorientedprogrammingandhowtousetheBorlandextensions.Sincethetopicofobjectorientedprogrammingisaverylargeanddiversefieldofstudyandonlyalimitedspaceisavailabletodiscussitinthistutorial,thesechapterswillgiveyouonlyabriefoverviewofwhatitisandhowtouseit.Youwillfind13completeexampleprogramstogetyoustartedinthisnewandverymeaningfulendeavorandthisintroductionshouldwhetyourappetitetocontinueyourstudyinmoredepth.IfyouareusinganearlyversionofTURBOPascalwithouttheobjectorientedextensions,itwouldpayyoutoupgradesoyoucanlearnhowtousethisnewprogrammingmethod.Objectorientedprogramminghasthepotentialtogreatlyimprovethequalityofyourcodeandtoreducethedebuggingtimerequired.PREPARATIONFORUSEOFTHISTUTORIA1.CopytheexamplefilesintoyourTURBOPascalworkingdirectoryandyouarereadytobegin,providedofcoursethatyouhavealreadylearnedhowtostarttheTURBOsystemandhowtoeditaPascalfile.IfyouarenotusingTURBOPascal,youwillstillbeabletocompileandexecutemanyofthesePascalfiles,sincemostoftheexamplesusestandardPascalsyntax.TherewillbesomestatementsusedwhichareuniquetoTURBOPascalandwillnotworkwithyourcompiler.Thiswillbeespeciallytruewhenyoucometothechapteronstandardinputandoutputsincethisiswheremostcompilersdiffer.Unfortunately,thisisoneofthemostimportantaspectsofanyprogramminglanguage,sinceitisrequiredtogetdataintoandoutofthecomputertodoanythinguseful.Youwillalsofindthatchapter13,coveringthetopicofunits,isuniquetoTURBOPascalandwillnotworkwithanyPascalcompilersotherthanTURBOPascal.WHATABOUTTHEPROGRAMMINGEXERCISES?Itishighlysuggestedthatyoudotheprogrammingexercisesafteryoucompletethestudyforeachchapter.Theyarecarefullyselectedtotestyourunderstandingofthematerialcoveredinthatchapter.Ifyoudonotwrite,enter,debug,andruntheseprograms,youW川OnlybeproficientatreadingPascal.Ifyoudotheexercisescompletely,youwillhaveagoodstartatbeingaPascalprogramwriter.ItshouldalsobementionedthatthistutorialwillnotteachyoueverythingyouwilleverneedtoknowaboutPascal.Youwillcontinuetolearnnewtechniquesaslongasyoucontinuetowriteprograms.Experienceisthebestteacherherejustasitisinanyendeavor.ThistutorialwillteachyouenoughaboutPascalthatyoushouldfeelverycomfortableasyousearchthroughthereferencemanualforsometopic.YouwillalsobeabletoreadandunderstandanyPascalprogramyoufindintextbooksormagazines.AlthoughtheprimarygoalofthistutorialistoteachyouthesyntaxanduseofPascal,themostimportantbyproductistheknowledgeofPascalterminologyyouwillgain.ThisterminologywillenableyoutolearnevenmoreaboutPascalandprogrammingingeneral.THEANSWERSTOPROGRAMMINGEXERCISESThefilepasans.zipcontainsananswertoeachoftheprogrammingexercisesgivenattheendofthechapters.Youshouldattempttodooriginalworkoneachoftheexercisesbeforereferringtotheseanswers,inordertogainyourownprogrammingexperience.Theseanswersaregivenforyourinformationincaseyouarecompletelystuckonhowtosolveaparticularproblem.Theseanswersarenotmeanttobetheonlyanswer,sincetherearemanywaystoprogramanything,buttheyaremeanttoillustrateonewaytosolvethesuggestedprogrammingproblem.TheanswersareallincompilablefilesnamedintheformatCHnn_m.PASwhereisthechapternumber,andmistheexercisenumber.Ifthereismorethanoneanswerrequired,anA,B,orCisincludedfollowingtheexercisenumber.AdVanCetoChaPter1RetUmtotheTableOfContentsCopyright©1986-1997CoronadoEnterprises-1.astupdate,March16,1997GordonDodriH-dodrill-PleaSeemailanycommentsorSIlggeStiOns.PascalTutorial-Chapter1WhatIsAComputerProgram?THISCHAPTERISFORNEWPROGRAMMERSIfyouareacompletenovicetocomputersyouwillfindtheinformationinthischapteruseful.Ifhowever,youhavehadsomeexperiencewithprogramming,youcancompletelyignorethischapter.ItwilldealwithafewfundamentalsofcomputersingeneralandwillintroducenothingthatisspecifictoPascal.WHATISACOMPUTERPROGRAM?Acomputerisnothingbutaverydumbmachinethathastheabilitytoperformmathematicaloperationsveryrapidlyandveryaccurately,butitcandonothingwithouttheaidofaprogramwrittenbyahumanbeing.Moreover,ifthehumanbeingwritesaprogramthatturnsgooddataintogarbage,thecomputerwillveryobediently,andveryrapidly,turnthegooddataintogarbage.Itispossibletowriteacomputerprogramwithonesmallerrorinitthatwilldothatverything,andinsomecasesappeartobegeneratinggooddata.Itisuptothehumanprogrammertodesignaprogramtoachievethedesiredresults.Acomputerprogramissimplya"recipe"whichthecomputerwilluseontheinputdatatoderivethedesiredoutputdata.Itissimilartotherecipeforbakingacake.Theinputdataiscomparabletotheingredients,includingtheheatsuppliedbytheoven.Theprogramiscomparabletotherecipeinstructionstomix,stir,wait,heat,cool,andallotherpossibleoperationsontheingredients.Theoutputofthecomputerprogramcanbecomparedtothefinalcakesittingonthecounterreadytobecutandserved.Acomputerprogramisthereforecomposedoftwoparts,thedatauponwhichtheprogramoperates,andtheprogramthatoperatesonthedata.Thedataandprogramareinseparableasimpliedbythelastsentence.WHATARECONSTANTS?Nearlyanycomputerprogramrequiressomenumbersthatneverchangethroughouttheprogram.Theycanbedefinedonceandusedasoftenasneededduringtheoperationoftheprogram.Toreturntotherecipeanalogy,onceyouhavedefinedhowbigatablespoonis,youcanusethesametablespoonwithoutregardtowhatyouaremeasuringwithit.Whenwritingacomputerprogram,youcandefinethevalueofPl=3.141592,andcontinuetouseitwhereveritmakessenseknowingthatitisavailable,andcorrect.WHATAREVARIAB1.ES?Inadditiontoconstants,nearlyeverycomputerprogramusessomenumbersthatchangeinvaluethroughouttheprogram.Theycanbedefinedasvariables,thenchangedtoanyvaluesthatmakesensetotheproperoperationoftheprogram.Anexamplewouldbethenumberofeggsintheaboverecipe.Ifasinglelayerofcakerequired2eggs,thenatriplelayercakewouldrequire6eggs.Thenumberofeggswouldthereforebeavariable.HOWDOWEDEFINECONSTANTSORVARIAB1.ES?Allconstantsandvariableshaveanameandavalue.Inthelastexample,thenameofthevariablewas"eggs",andthevaluewaseither2or6dependingonwhenwelookedatthestoreddata.Inacomputerprogramtheconstantsandvariablesaregivennamesinmuchthesamemanner,afterwhichtheycanstoreanyvaluewithinthedefinedrange.Anycomputerprogramminglanguagehasameansbywhichconstantsorvariablescanbefirstnamed,thenassignedavalue.ThemeansfordoingthisinPascalwillbegiventhroughouttheremainderofthistutorial.WHATISSOGOODABOUTPASCA1.?Somecomputerlanguagesallowtheprogrammertodefineconstantsandvariablesinaveryhaphazardmannerandthencombinedatainanevenmorehaphazardmanner.Forexample,ifyouaddedthenumberofeggs,intheaboverecipe,tothenumberofcupsofflour,youwouldarriveatavalidmathematicaladdition,butatotallymeaninglessnumber.Someprogramminglanguageswouldallowyoutodojustsuchanadditionandobedientlyprintoutthemeaninglessanswer.SincePascalrequiresyoutosetupyourconstantsandvariablesinaveryprecisemanner,thepossibilityofsuchameaninglessanswerisminimized.AwellwrittenPascalprogramhasmanycrosscheckstominimizethepossibilityofacompletelyscrambledandmeaninglessoutput.Noticehowever,inthelaststatement,thata"wellwritten"Pascalprogramwasunderdiscussion.Itisstilluptotheprogrammertodefinethedatastructureinsuchawaythattheprogramcanhelppreventgarbagegeneration.Intheend,theprogramwillbenobetterthantheanalysisthatwentintotheprogramdesign.Ifyouareanoviceprogrammer,donotbeintimidatedbyanyoftheabovestatements.Pascalisawelldesigned,usefultoolthathasbeenusedsuccessfullybymanycomputernovicesandprofessionals.Withthesefewwarnings,youarereadytobegin.AdVanCetoChaPter2RetUmtotheTabIeOfCC)meritsCopyright©1986-1997CoronadoEnterprises-1.astupdate,March16,1997GordonDodriH-dodriH-PleaSeemailanycommentsOrSUqqeStiOns.PascalTutorial-Chapter2GettingStartedInPascalYOURFIRSTPASCA1.PROGRAMExampleprogram>TRIVIA1.PAS1.etsgetrightintoaprogramthatreallydoesnothing,butisanexampleofthemosttrivialPascalprogram.1.oadTurboPascal,thenloadTRIVIA1.PASintotheintegratedenvironmentasaworkfile.ThisassumesyouhavebeensuccessfulinlearninghowtousetheTURBOPascalsystem.YoushouldnowhavethemosttrivialPascalprogrampossibleonyourdisplay,andwecantakealookateachparttodefinewhatitdoes.ThefirstlineisrequiredinthestandardPascaldefinitionandcontainstheprogramnamewhichcanbeanynameyoulike,aslongasitfollowstherulesforanidentifiergiveninthenextsection.Itcanhavenoblanks,otherwiseitwouldbeconsideredastwowordsanditwouldconfusethecompiler.ThefirstwordprogramisthefirstofthereservedwordsmentionedearlieranditistheindicatortothePascalcompilerthatthisisthenameoftheprogram.Thesecondword,Puppy_Dog,istheprogramnameitself.Noticethatthelineendswithasemicolon.Pascalusesthesemicolonasastatementseparatorandalthoughallstatementsdonotactuallyendinasemicolon,mostdo,andtheproperuseofthesemicolonwillclearuplaterinyourmind.TURBOPascaldoesnotrequiretheprogramstatement,buttoremaincompatiblewithstandardPascal,itwillsimplyignoretheentirestatement.ItisrecommendedthatyouincludeaprogramnamebothtoaidyourthinkinginstandardPascal,andtoaddalittlemoreindicationofthepurposeofeachprogram.WHATISANIDENTIFIER?Allidentifiers,includingtheprogramname,procedureandfunctionnames,typedefinitions,andconstantandvariablenames,willstartwithanalphabeticalcharacterandbecomposedofanycombination