Вы находитесь на странице: 1из 17

5/1/2016

ComputerProgramming

ComputerProgramming

WhyProgramming?
Youmayalreadyhaveusedsoftware,perhapsforwordprocessingorspreadsheets,tosolve
problems.Perhapsnowyouarecurioustolearnhowprogrammerswritesoftware.Aprogramisa
setofstepbystepinstructionsthatdirectsthecomputertodothetasksyouwantittodoand
producetheresultsyouwant.
Thereareatleastthreegoodreasonsforlearningprogramming:
Programminghelpsyouunderstandcomputers.Thecomputerisonlyatool.Ifyoulearn
howtowritesimpleprograms,youwillgainmoreknowledgeabouthowacomputerworks.
Writingafewsimpleprogramsincreasesyourconfidencelevel.Manypeoplefindgreat
personalsatisfactionincreatingasetofinstructionsthatsolveaproblem.
Learningprogrammingletsyoufindoutquicklywhetheryoulikeprogrammingandwhether
youhavetheanalyticalturnofmindprogrammersneed.Evenifyoudecidethat
programmingisnotforyou,understandingtheprocesscertainlywillincreaseyour
appreciationofwhatprogrammersandcomputerscando.
Asetofrulesthatprovidesawayoftellingacomputerwhatoperationstoperformiscalleda
programminglanguage.Thereisnot,however,justoneprogramminglanguagetherearemany.In
thischapteryouwilllearnaboutcontrollingacomputerthroughtheprocessofprogramming.You
mayevendiscoverthatyoumightwanttobecomeaprogrammer.
Animportantpointbeforeweproceed:Youwillnotbeaprogrammerwhenyoufinishreadingthis
chapterorevenwhenyoufinishreadingthefinalchapter.Programmingproficiencytakespractice
andtrainingbeyondthescopeofthisbook.However,youwillbecomeacquaintedwithhow
programmersdevelopsolutionstoavarietyofproblems.
WhatProgrammersDo
Ingeneral,theprogrammer'sjobistoconvertproblemsolutionsintoinstructionsforthecomputer.
Thatis,theprogrammerpreparestheinstructionsofacomputerprogramandrunsthose
instructionsonthecomputer,teststheprogramtoseeifitisworkingproperly,andmakes
correctionstotheprogram.Theprogrammeralsowritesareportontheprogram.Theseactivities
arealldoneforthepurposeofhelpingauserfillaneed,suchaspayingemployees,billing
customers,oradmittingstudentstocollege.
Theprogrammingactivitiesjustdescribedcouldbedone,perhaps,assoloactivities,buta
programmertypicallyinteractswithavarietyofpeople.Forexample,ifaprogramispartofa
systemofseveralprograms,theprogrammercoordinateswithotherprogrammerstomakesurethat
theprogramsfittogetherwell.Ifyouwereaprogrammer,youmightalsohavecoordination
meetingswithusers,managers,systemsanalysts,andwithpeerswhoevaluateyourworkjustas
youevaluatetheirs.
Letusturntotheprogrammingprocess.
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

1/17

5/1/2016

ComputerProgramming

TheProgrammingProcess
Developingaprograminvolvesstepssimilartoanyproblemsolvingtask.Therearefivemain
ingredientsintheprogrammingprocess:
1.Definingtheproblem
2.Planningthesolution
3.Codingtheprogram
4.Testingtheprogram
5.Documentingtheprogram
Letusdiscusseachoftheseinturn.
1.DefiningtheProblem
Supposethat,asaprogrammer,youarecontactedbecauseyourservicesareneeded.You
meetwithusersfromtheclientorganizationtoanalyzetheproblem,oryoumeetwitha
systemsanalystwhooutlinestheproject.Specifically,thetaskofdefiningtheproblem
consistsofidentifyingwhatitisyouknow(inputgivendata),andwhatitisyouwantto
obtain(outputtheresult).Eventually,youproduceawrittenagreementthat,amongother
things,specifiesthekindofinput,processing,andoutputrequired.Thisisnotasimple
process.
2.PlanningtheSolution
Two
common
waysof
planning
the
solution
toa
problem
areto
drawa
flowchart
andto
write

http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

2/17

5/1/2016

ComputerProgramming

Figure1:FlowChartSymbolsandFlowChartForMailingLetter
pseudocode,orpossiblyboth.Essentially,aflowchartisapictorialrepresentationofastep
bystepsolutiontoaproblem.Itconsistsofarrowsrepresentingthedirectiontheprogram
takesandboxesandothersymbolsrepresentingactions.Itisamapofwhatyourprogramis
goingtodoandhowitisgoingtodoit.TheAmericanNationalStandardsInstitute(ANSI)
hasdevelopedastandardsetofflowchartsymbols.Figure1showsthesymbolsandhow
theymightbeusedinasimpleflowchartofacommoneverydayactpreparingaletterfor
mailing.
PseudocodeisanEnglishlikenonstandardlanguagethatletsyoustateyoursolutionwith
moreprecisionthanyoucaninplainEnglishbutwithlessprecisionthanisrequiredwhen
usingaformalprogramminglanguage.Pseudocodepermitsyoutofocusontheprogram
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

3/17

5/1/2016

ComputerProgramming

logicwithouthavingtobeconcernedjustyetabouttheprecisesyntaxofaparticular
programminglanguage.However,pseudocodeisnotexecutableonthecomputer.Wewill
illustratetheselaterinthischapter,whenwefocusonlanguageexamples.
3.CodingtheProgram
Astheprogrammer,yournextstepistocodetheprogramthatis,toexpressyoursolutionin
aprogramminglanguage.Youwilltranslatethelogicfromtheflowchartorpseudocodeor
someothertooltoaprogramminglanguage.Aswehavealreadynoted,aprogramming
languageisasetofrulesthatprovidesawayofinstructingthecomputerwhatoperationsto
perform.Therearemanyprogramminglanguages:BASIC,COBOL,Pascal,FORTRAN,
andCaresomeexamples.Youmayfindyourselfworkingwithoneormoreofthese.We
willdiscussthedifferenttypesoflanguagesindetaillaterinthischapter.
Althoughprogramminglanguagesoperategrammatically,somewhatliketheEnglish
language,theyaremuchmoreprecise.Togetyourprogramtowork,youhavetofollow
exactlytherulesthesyntaxofthelanguageyouareusing.Ofcourse,usingthelanguage
correctlyisnoguaranteethatyourprogramwillwork,anymorethanspeaking
grammaticallycorrectEnglishmeansyouknowwhatyouaretalkingabout.Thepointisthat
correctuseofthelanguageistherequiredfirststep.Thenyourcodedprogrammustbe
keyed,probablyusingaterminalorpersonalcomputer,inaformthecomputercan
understand.
Onemorenotehere:Programmersusuallyuseatexteditor,whichissomewhatlikeaword
processingprogram,tocreateafilethatcontainstheprogram.However,asabeginner,you
willprobablywanttowriteyourprogramcodeonpaperfirst.
4.TestingtheProgram
Someexpertsinsistthatawelldesignedprogramcanbewrittencorrectlythefirsttime.In
fact,theyassertthattherearemathematicalwaystoprovethataprogramiscorrect.
However,theimperfectionsoftheworldarestillwithus,somostprogrammersgetusedto
theideathattheirnewlywrittenprogramsprobablyhaveafewerrors.Thisisabit
discouragingatfirst,sinceprogrammerstendtobeprecise,careful,detailorientedpeople
whotakeprideintheirwork.Still,therearemanyopportunitiestointroducemistakesinto
programs,andyou,justasthosewhohavegonebeforeyou,willprobablyfindseveralof
them.
Eventually,aftercodingtheprogram,youmustpreparetotestitonthecomputer.Thisstep
involvesthesephases:
Deskchecking.Thisphase,similartoproofreading,issometimesavoidedbythe
programmerwhoislookingforashortcutandiseagertoruntheprogramonthe
computeronceitiswritten.However,withcarefuldeskcheckingyoumaydiscover
severalerrorsandpossiblysaveyourselftimeinthelongrun.Indeskcheckingyou
simplysitdownandmentallytrace,orcheck,thelogicoftheprogramtoattemptto
ensurethatitiserrorfreeandworkable.Manyorganizationstakethisphaseastep
furtherwithawalkthrough,aprocessinwhichagroupofprogrammersyourpeers
reviewyourprogramandoffersuggestionsinacollegialway.
Translating.Atranslatorisaprogramthat(1)checksthesyntaxofyourprogramto
makesuretheprogramminglanguagewasusedcorrectly,givingyouallthesyntax
errormessages,calleddiagnostics,and(2)thentranslatesyourprogramintoaform
thecomputercanunderstand.Abyproductoftheprocessisthatthetranslatortells
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

4/17

5/1/2016

ComputerProgramming

youifyouhaveimproperlyusedtheprogramminglanguageinsomeway.Thesetypes
ofmistakesarecalledsyntaxerrors.Thetranslatorproducesdescriptiveerror
messages.Forinstance,ifinFORTRANyoumistakenlywriteN=2*(I+J))whichhas
twoclosingparenthesesinsteadofoneyouwillgetamessagethatsays,
"UNMATCHEDPARENTHESES."(Differenttranslatorsmayprovidedifferent
wordingforerrormessages.)Programsaremostcommonlytranslatedbyacompiler.
Acompilertranslatesyourentireprogramatonetime.Thetranslationinvolvesyour
originalprogram,calledasourcemodule,whichistransformedbyacompilerintoan
objectmodule.Prewrittenprogramsfromasystemlibrarymaybeaddedduringthe
link/loadphase,whichresultsinaloadmodule.Theloadmodulecanthenbeexecuted
bythecomputer.
Debugging.Atermusedextensivelyinprogramming,debuggingmeansdetecting,
locating,andcorrectingbugs(mistakes),usuallybyrunningtheprogram.Thesebugs
arelogicerrors,suchastellingacomputertorepeatanoperationbutnottellingithow
tostoprepeating.Inthisphaseyouruntheprogramusingtestdatathatyoudevise.
Youmustplanthetestdatacarefullytomakesureyoutesteverypartoftheprogram.
5.DocumentingtheProgram
Documentingisanongoing,necessaryprocess,although,asmanyprogrammersare,you
maybeeagertopursuemoreexcitingcomputercenteredactivities.Documentationisa
writtendetaileddescriptionoftheprogrammingcycleandspecificfactsabouttheprogram.
Typicalprogramdocumentationmaterialsincludetheoriginandnatureoftheproblem,a
briefnarrativedescriptionoftheprogram,logictoolssuchasflowchartsandpseudocode,
datarecorddescriptions,programlistings,andtestingresults.Commentsintheprogram
itselfarealsoconsideredanessentialpartofdocumentation.Manyprogrammersdocument
astheycode.Inabroadersense,programdocumentationcanbepartofthedocumentation
foranentiresystem.
Thewiseprogrammercontinuestodocumenttheprogramthroughoutitsdesign,
development,andtesting.Documentationisneededtosupplementhumanmemoryandto
helporganizeprogramplanning.Also,documentationiscriticaltocommunicatewithothers
whohaveaninterestintheprogram,especiallyotherprogrammerswhomaybepartofa
programmingteam.And,sinceturnoverishighinthecomputerindustry,written
documentationisneededsothatthosewhocomeafteryoucanmakeanynecessary
modificationsintheprogramortrackdownanyerrorsthatyoumissed.
ProgrammingasaCareer
Thereisashortageofqualifiedpersonnelinthecomputerfield.Beforeyoujointheirranks,
considertheadvantagesofthecomputerfieldandwhatittakestosucceedinit.
TheJoysoftheField
Althoughmanypeoplemakecareerchangesintothecomputerfield,fewchoosetoleaveit.Infact,
surveysofcomputerprofessionals,especiallyprogrammers,consistentlyreportahighlevelofjob
satisfaction.Thereareseveralreasonsforthiscontentment.Oneisthechallengemostjobsinthe
computerindustryarenotroutine.Anotherissecurity,sinceestablishedcomputerprofessionals
canusuallyfindwork.Andthatworkpayswellyouwillprobablynotberich,butyoushouldbe
comfortable.Thecomputerindustryhashistoricallybeenarewardingplaceforwomenand
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

5/17

5/1/2016

ComputerProgramming

minorities.And,finally,theindustryholdsendlessfascinationsinceitisalwayschanging.
WhatItTakes
Youneed,ofcourse,somecredentials,mostoftenatwoorfouryeardegreeincomputer
informationsystemsorcomputerscience.Therequirementsandsalariesvarybytheorganization
andtheregion,sowewillnotdwellonthesehere.Beyondthat,thepersonmostlikelytolandajob
andmoveupthecareerladderistheonewithexcellentcommunicationskills,bothoralandwritten
.Thesearealsothequalitiesthatcanbeobservedbypotentialemployersinaninterview.
Promotionsaresometimestiedtoadvanceddegrees(anM.B.A.oranM.S.incomputerscience).
OpenDoors
Theoveralloutlookforthecomputerfieldispromising.TheBureauofLaborStatisticsshows,
throughtheyear2010,a72percentincreaseinprogrammersanda69percentincreaseinsystem
usetoday,andwewilldiscussthemostpopularoneslaterInthechapter.Beforeweturntospecific
languages,however,weneedtodiscusslevelsoflanguage.
LevelsofLanguage
Programminglanguagesaresaidtobe"lower"or"higher,"dependingonhowclosetheyaretothe
languagethecomputeritselfuses(Osand1s=low)ortothelanguagepeopleuse(moreEnglish
likehigh).Wewillconsiderfivelevelsoflanguage.Theyarenumbered1through5tocorrespond
tolevels,orgenerations.Intermsofeaseofuseandcapabilities,eachgenerationisan
improvementoveritspredecessors.Thefivegenerationsoflanguagesare
1.Machinelanguage
2.Assemblylanguages
3.Highlevellanguages
4.Veryhighlevellanguages
5.Naturallanguages
Letuslookateachofthesecategories.
MachineLanguage
Humansdonotliketodealinnumbersalonetheypreferlettersandwords.But,strictlyspeaking,
numbersarewhatmachinelanguageis.Thislowestleveloflanguage,machinelanguage,
representsdataandprograminstructionsas1sandOsbinarydigitscorrespondingtotheonandoff
electricalstatesinthecomputer.Eachtypeofcomputerhasitsownmachinelanguage.Intheearly
daysofcomputing,programmershadrudimentarysystemsforcombiningnumberstorepresent
instructionssuchasaddandcompare.Primitivebytoday'sstandards,theprogramswerenot
convenientforpeopletoreadanduse.Thecomputerindustryquicklymovedtodevelopassembly
languages.
AssemblyLanguages
Today,

http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

6/17

5/1/2016

ComputerProgramming

Figure2:ExampleAssemblyLanguageProgram
assemblylanguagesareconsideredverylowlevelthatis,theyarenotasconvenientforpeopleto
useasmorerecentlanguages.Atthetimetheyweredeveloped,however,theywereconsidereda
greatleapforward.ToreplacetheIsandOsusedinmachinelanguage,assemblylanguagesuse
mnemoniccodes,abbreviationsthatareeasytoremember:AforAdd,CforCompare,MPfor
Multiply,STOforstoringinformationinmemory,andsoon.AlthoughthesecodesarenotEnglish
words,theyarestillfromthestandpointofhumanconveniencepreferabletonumbers(Osand1s)
alone.Furthermore,assemblylanguagespermittheuseofnamesperhapsRATEorTOTALfor
memorylocationsinsteadofactualaddressnumbers.justlikemachinelanguage,eachtypeof
computerhasitsownassemblylanguage.
Theprogrammerwhousesanassemblylanguagerequiresatranslatortoconverttheassembly
languageprogramintomachinelanguage.Atranslatorisneededbecausemachinelanguageisthe
onlylanguagethecomputercanactuallyexecute.Thetranslatorisanassemblerprogram,also
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

7/17

5/1/2016

ComputerProgramming

referredtoasanassembler.Ittakestheprogramswritteninassemblylanguageandturnstheminto
machinelanguage.Programmersneednotworryaboutthetranslatingaspecttheyneedonlywrite
programsinassemblylanguage.Thetranslationistakencareofbytheassembler.
Althoughassemblylanguagesrepresentastepforward,theystillhavemanydisadvantages.Akey
disadvantageisthatassemblylanguageisdetailedintheextreme,makingassemblyprogramming
repetitive,tedious,anderrorprone.ThisdrawbackisapparentintheprograminFigure2.
Assemblylanguagemaybeeasiertoreadthanmachinelanguage,butitisstilltedious.
HighLevelLanguages
Thefirstwidespreaduseofhighlevellanguagesintheearly1960stransformedprogramminginto
somethingquitedifferentfromwhatithadbeen.ProgramswerewritteninanEnglishlikemanner,
thusmakingthemmoreconvenienttouse.Asaresult,aprogrammercouldaccomplishmorewith
lesseffort,andprogramscouldnowdirectmuchmorecomplextasks.
Thesesocalledthirdgenerationlanguagesspurredthegreatincreaseindataprocessingthat
characterizedthe1960sand1970s.Duringthattimethenumberofmainframesinuseincreased
fromhundredstotensofthousands.Theimpactofthirdgenerationlanguagesonoursocietyhas
beenenormous.
Ofcourse,atranslatorisneededtotranslatethesymbolicstatementsofahighlevellanguageinto
computerexecutablemachinelanguagethistranslatorisusuallyacompiler.Therearemany
compilersforeachlanguageandoneforeachtypeofcomputer.Sincethemachinelanguage
generatedbyonecomputer'sCOBOLcompiler,forinstance,isnotthemachinelanguageofsome
othercomputer,itisnecessarytohaveaCOBOLcompilerforeachtypeofcomputeronwhich
COBOLprogramsaretoberun.Keepinmind,however,thateventhoughagivenprogramwould
becompiledtodifferentmachinelanguageversionsondifferentmachines,thesourceprogram
itselftheCOBOLversioncanbeessentiallyidenticaloneachmachine.
Somelanguagesarecreatedtoserveaspecificpurpose,suchascontrollingindustrialrobotsor
creatinggraphics.Manylanguages,however,areextraordinarilyflexibleandareconsideredtobe
generalpurpose.InthepastthemajorityofprogrammingapplicationswerewritteninBASIC,
FORTRAN,orCOBOLallgeneralpurposelanguages.Inadditiontothesethree,anotherpopular
highlevellanguageisC,whichwewilldiscusslater.
VeryHighLevelLanguages
Languagescalledveryhighlevellanguagesareoftenknownbytheirgenerationnumber,thatis,
theyarecalledfourthgenerationlanguagesor,moresimply,4GLs.
Definition
Willtherealfourthgenerationlanguagespleasestandup?Thereisnoconsensusaboutwhat
constitutesafourthgenerationlanguage.The4GLsareessentiallyshorthandprogramming
languages.Anoperationthatrequireshundredsoflinesinathirdgenerationlanguagesuchas
COBOLtypicallyrequiresonlyfivetotenlinesina4GL.However,beyondthebasiccriterionof
conciseness,4GLsaredifficulttodescribe.
Characteristics
Fourthgenerationlanguagessharesomecharacteristics.Thefirstisthattheymakeatruebreak
withthepriorgenerationtheyarebasicallynonprocedural.Aprocedurallanguagetellsthe
computerhowataskisdone:Addthis,comparethat,dothisifsomethingistrue,andsofortha
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

8/17

5/1/2016

ComputerProgramming

veryspecificstepbystepprocess.Thefirstthreegenerationsoflanguagesareallprocedural.Ina
nonprocedurallanguage,theconceptchanges.Here,usersdefineonlywhattheywantthe
computertodotheuserdoesnotprovidethedetailsofjusthowitistobedone.Obviously,itisa
loteasierandfasterjusttosaywhatyouwantratherthanhowtogetit.Thisleadsustotheissueof
productivity,akeycharacteristicoffourthgenerationlanguages.
Productivity
Folklorehasitthatfourthgenerationlanguagescanimproveproductivitybyafactorof5to50.
Thefolkloreistrue.Mostexpertssaytheaverageimprovementfactorisabout10thatis,youcan
betentimesmoreproductiveinafourthgenerationlanguagethaninathirdgenerationlanguage.
Considerthisrequest:Produceareportshowingthetotalunitssoldforeachproduct,bycustomer,
ineachmonthandyear,andwithasubtotalforeachcustomer.Inaddition,eachnewcustomer
muststartonanewpage.A4GLrequestlookssomethinglikethis:

TABLEFILESALES
SUMUNITSBYMONTHBYCUSTOMERBYPRODUCT
ONCUSTOMERSUBTOTALPAGEBREAK
END

Eventhoughsometrainingisrequiredtodoeventhismuch,youcanseethatitisprettysimple.
ThethirdgenerationlanguageCOBOL,however,typicallyrequiresover500statementstofulfill
thesamerequest.Ifwedefineproductivityasproducingequivalentresultsinlesstime,then
fourthgenerationlanguagesclearlyincreaseproductivity.
Downside
Fourthgenerationlanguagesarenotallpeachesandcreamandproductivity.The4GLsarestill
evolving,andthatwhichisstillevolvingcannotbefullydefinedorstandardized.Whatismore,
sincemany4GLsareeasytouse,theyattractalargenumberofnewusers,whomaythen
overcrowdthecomputersystem.Oneofthemaincriticismsisthatthenewlanguageslackthe
necessarycontrolandflexibilitywhenitcomestoplanninghowyouwanttheoutputtolook.A
commonperceptionof4GLsisthattheydonotmakeefficientuseofmachineresourceshowever,
thebenefitsofgettingaprogramfinishedmorequicklycanfaroutweightheextracostsofrunning
it.
Benefits
Fourthgenerationlanguagesarebeneficialbecause
Theyareresultsorientedtheyemphasizewhatinsteadofhow.
Theyimproveproductivitybecauseprogramsareeasytowriteandchange.
Theycanbeusedwithaminimumoftrainingbybothprogrammersandnonprogrammers.
Theyshieldusersfromneedinganawarenessofhardwareandprogramstructure.
Itwasnotlongagothatfewpeoplebelievedthat4GLswouldeverbeabletoreplacethird
generationlanguages.These4GLlanguagesarebeingused,butinaverylimitedway.
QueryLanguages
Avariationonfourthgenerationlanguagesarequerylanguages,whichcanbeusedtoretrieve
informationfromdatabases.Dataisusuallyaddedtodatabasesaccordingtoaplan,andplanned
reportsmayalsobeproduced.Butwhataboutauserwhoneedsanunscheduledreportorareport
thatdifferssomehowfromthestandardreports?Ausercanlearnaquerylanguagefairlyeasilyand
thenbeabletoinputarequestandreceivetheresultingreportrightonhisorherownterminalor
personalcomputer.Astandardizedquerylanguage,whichcanbeusedwithseveraldifferent
commercialdatabaseprograms,isStructuredQueryLanguage,popularlyknownasSQL.Other
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

9/17

5/1/2016

ComputerProgramming

popularquerylanguagesareQuerybyExample,knownasQBE,andIntellect.
NaturalLanguages
Theword"natural"hasbecomealmostaspopularincomputingcirclesasithasinthe
supermarket.Fifthgenerationlanguagesare,asyoumayguess,evenmoreilldefinedthanfourth
generationlanguages.Theyaremostoftencallednaturallanguagesbecauseoftheirresemblanceto
the"natural"spokenEnglishlanguage.And,tothemanagernewtocomputersforwhomthese
languagesarenowaimed,naturalmeanshumanlike.Insteadofbeingforcedtokeycorrect
commandsanddatanamesincorrectorder,amanagertellsthecomputerwhattodobykeyingin
hisorherownwords.
Amanagercansaythesamethingany
numberofways.Forexample,"Getme
tennisracketsalesforJanuary"worksjust
aswellas"IwantJanuarytennisracket
revenues."Sucharequestmaycontain
misspelledwords,lackarticlesandverbs,
andevenuseslang.Thenaturallanguage
translateshumaninstructionsbad
grammar,slang,andallintocodethe
computerunderstands.Ifitisnotsure
whattheuserhasinmind,itpolitelyasks
forfurtherexplanation.
Naturallanguagesaresometimesreferred
toasknowledgebasedlanguages,because
naturallanguagesareusedtointeractwith
abaseofknowledgeonsomesubject.The
useofanaturallanguagetoaccessa
knowledgebaseiscalledaknowledge
Figure3:ExampleofNaturalLanguageInteraction basedsystem.
Considerthisrequestthatcouldbegiveninthe4GLFocus:"SUMORDERSBYDATEBY
REGION."Ifwealtertherequestand,stillinFocus,saysomethinglike"Givemethedatesandthe
regionsafteryou'veaddeduptheorders,"thecomputerwillspitbacktheuserfriendlyversionof
"You'vegottobekidding"andgiveup.Butsomenaturallanguagescanhandlesucharequest.
Userscanrelaxthestructureoftheirrequestsandincreasethefreedomoftheirinteractionwiththe
data.
Hereisatypicalnaturallanguagerequest:

REPORTTHEBASESALARY,COMMISSIONSANDYEARSOF
SERVICEBROKENDOWNBYSTATEANDCITYFORSALESCLERKS
INNEWJERSEYANDMASSACHUSETTS.

YoucanhardlygetclosertoconversationalEnglishthanthat.
AnexampleofanaturallanguageisshowninFigure3.Naturallanguagesexcelateasydata
access.Indeed,themostcommonapplicationfornaturallanguagesisinteractingwithdatabases.
ChoosingaLanguage
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

10/17

5/1/2016

ComputerProgramming

Howdoyouchoosethelanguagewithwhichtowriteyourprogram?
Thereareseveralpossibilities:
Inaworkenvironment,yourmanagermaydecreethateveryoneonyourprojectwillusea
certainlanguage.
Youmayuseacertainlanguage,particularlyinabusinessenvironment,basedontheneedto
interfacewithotherprogramsiftwoprogramsaretoworktogether,itiseasiestiftheyare
writteninthesamelanguage.
Youmaychoosealanguagebasedonitssuitabilityforthetask.Forexample,abusiness
programthathandleslargefilesmaybebestwritteninthebusinesslanguageCOBOL.
Ifaprogramistoberunondifferentcomputers,itmustbewritteninalanguagethatis
portablesuitableoneachtypeofcomputersothattheprogramneedbewrittenonlyonce.
Youmaybelimitedbytheavailabilityofthelanguage.Notalllanguagesareavailableinall
installationsoronallcomputers.
Thelanguagemaybelimitedtotheexpertiseoftheprogrammerthatis,theprogrammay
havetobewritteninalanguagetheavailableprogrammerknows.
Perhapsthesimplestreason,onethatappliestomanyamateurprogrammers,isthatthey
knowthelanguagecalledBASICbecauseitcamewithorwasinexpensivelypurchased
withtheirpersonalcomputers.
MajorProgrammingLanguages
Thefollowingsectionson
individuallanguageswillgive
youanoverviewofthethird
generationlanguagesincommon
usetoday:FORTRAN(a
scientificlanguage),COBOL(a
businesslanguage),BASIC
(simplelanguageusedfor
educationandbusiness),Pascal
(education),Ada(military),and
C(generalpurposed).
Thischapterwillpresent
programswritteninsomeof
theselanguages.Youwillalso
seeoutputproducedbyeach
program.Eachprogramis
designedtofindtheaverageof
threenumberstheresulting
averageisshowninthesample
outputmatchingeachprogram.
Sinceallprogramsperformthe
sametask,youwillseesomeof
thedifferencesandsimilarities
amongthelanguages.Wedonot
expectyoutounderstandthese
programstheyareheremerely
toletyouglimpseeachlanguage.
Figure4presentstheflowchart
andpseudocodeforthetaskof
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

11/17

5/1/2016

ComputerProgramming

averagingnumbers.Aswe
discusseachlanguage,wewill
provideaprogramforaveraging
numbersthatfollowsthelogic
showninthisfigure.
FORTRAN:TheFirstHigh
LevelLanguage
DevelopedbyIBMand
introducedin1954,FORTRAN
forFORmulaTRANslatorwas
thefirsthighlevellanguage.
FORTRANisascientifically
orientedlanguageintheearly
daysuseofthecomputerwas
primarilyassociatedwith
engineering,mathematical,and
scientificresearchtasks.
FORTRANisnotedforits
brevity,andthischaracteristicis
partofthereasonwhyitremains
popular.Thislanguageisvery
goodatservingitsprimary
purpose,whichisexecutionof
complexformulassuchasthose
usedineconomicanalysisand
engineering.Althoughinthepast
itwasconsideredlimitedin
regardtofileprocessingordata
processing,itscapabilitieshave
beengreatlyimproved.

Figure4:FlowChartForAveragingNumbers

http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

Notallprogramsareorganizedin
thesameway.Organization
variesaccordingtothelanguage
used.Inmanylanguages(suchas
COBOL),programs
aredividedintoa
seriesofparts.
FORTRAN
programsarenot
composedof
differentparts
(althoughitis
possibletolink
FORTRAN
programstogether)
aFORTRAN
programconsistsof
12/17

5/1/2016

ComputerProgramming

statementsoneafter
theother.Different
typesofdataare
identifiedasthedata
isused.Descriptions
fordatarecords
appearinformat
statementsthat
accompanythe
READandWRITE
statements.Figure5
showsaFORTRAN
programanda
sampleoutputfrom
theprogram.

Figure5:ExampleFortranProgramToAverageNumbers

http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

COBOL:The
Languageof
Business
Inthe1950s
FORTRANhad
beendeveloped,but
therewasstillno
acceptedhighlevel
programming
languageappropriate
forbusiness.The
U.S.Departmentof
Defenseinparticular
wasinterestedin
creatingsucha
standardized
language,andsoit
calledtogether
representativesfrom
governmentand
variousindustries,
includingthe
computer
industry.These
representatives
formed
CODASYL
COnferenceof
DAtaSYstem
Languages.In
1959CODASYL
introduced
COBOLfor
COmmon
13/17

5/1/2016

ComputerProgramming

BusinessOriented
Language.

Figure6:ExampleCOBOLProgramtoAverageNumbers
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

TheU.S.
government
offered
encouragement
byinsistingthat
anyone
attemptingtowin
government
contractsfor
computerrelated
projectshadto
useCOBOL.The
American
National
Standards
Institutefirst
standardized
COBOLin1968
and,in1974,
issuedstandards
foranother
versionknownas
ANSICOBOL.
Aftermorethan
seven
controversial
yearsofindustry
debate,the
standardknown
asCOBOL85
wasapproved,
makingCOBOL
amoreusable
modernday
softwaretool.The
principalbenefit
ofstandardization
isthatCOBOLis
relatively
machine
independentthat
is,aprogram
writtenforone
typeofcomputer
canberunwith
onlyslight
modificationson
14/17

5/1/2016

ComputerProgramming

anothertypeforwhichaCOBOLcompilerhasbeendeveloped.
COBOLisverygoodforprocessinglargefilesandperformingrelativelysimplebusiness
calculations,suchaspayrollorinterest.AnoteworthyfeatureofCOBOListhatitisEnglishlike
farmoresothanFORTRANorBASIC.Thevariablenamesaresetupinsuchawaythat,evenif
youknownothingaboutprogramming,youcanstillunderstandwhattheprogramdoes.For
example:

IFSALESAMOUNTISGREATERTHANSALESQUOTA

COMPUTECOMMISSION=MAXRATE*SALESAMOUNT
ELSE

COMPUTECOMMISSION=MINRATE*SALESAMOUNT.

Onceyouunderstandprogrammingprinciples,itisnottoodifficulttoaddCOBOLtoyour
repertoire.COBOLcanbeusedforjustaboutanytaskrelatedtobusinessprogrammingindeed,it
isespeciallysuitedtoprocessingalphanumericdatasuchasstreetaddresses,purchaseditems,and
dollaramountsthedataofbusiness.However,thefeaturethatmakesCOBOLsousefulits
EnglishlikeappearanceandeasyreadabilityisalsoaweaknessbecauseaCOBOLprogramcanbe
incrediblyverbose.AprogrammerseldomknocksoutaquickCOBOLprogram.Infact,thereis
hardlysuchathingasaquickCOBOLprogramtherearejusttoomanyprogramlinestowrite,
eventoaccomplishasimpletask.Forspeedandsimplicity,BASIC,FORTRAN,andPascalare
probablybetterbets.
AsyoucanseeinFigure6,aCOBOLprogramisdividedintofourpartscalleddivisions.The
identificationdivisionidentifiestheprogrambynameandoftencontainshelpfulcommentsas
well.Theenvironmentdivisiondescribesthecomputeronwhichtheprogramwillbecompiledand
executed.Italsorelateseachfileoftheprogramtothespecificphysicaldevice,suchasthetape
driveorprinter,thatwillreadorwritethefile.Thedatadivisioncontainsdetailsaboutthedata
processedbytheprogram,suchastypeofcharacters(whethernumericoralphanumeric),number
ofcharacters,andplacementofdecimalpoints.Theproceduredivisioncontainsthestatementsthat
givethecomputerspecificinstructionstocarryoutthelogicoftheprogram.
IthasbeenfashionableforsometimetocriticizeCOBOL:Itisoldfashioned,cumbersome,and
inelegant.Infact,somecompanies,devotedtofast,nimbleprogramdevelopment,areconverting
tothemoretrendylanguageC.ButCOBOL,withmorethan30yearsofstayingpower,isstill
famousforitsclearcode,whichiseasytoreadanddebug.
BASIC:ForBeginnersandOthers
BASICBeginners'
Allpurpose
Symbolic
InstructionCodeis
acommon
languagethatis
easytolearn.
Developedat
Dartmouth
College,BASIC
wasintroducedby
JohnKemenyand
ThomasKurtzin
http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

15/17

5/1/2016

ComputerProgramming

1965andwas
originallyintended
forusebystudents
inanacademic
environment.Inthe
late1960sit
becamewidely
usedininteractive
timesharing
environmentsin
universitiesand
colleges.Theuse
ofBASIChas
extendedto
businessand
personalcomputer
systems.
Theprimary
featureofBASIC
isonethatmaybe
ofinteresttomany
readersofthis
book:BASICis
easytolearn,even
forapersonwho
hasnever
programmed
before.Thus,the
languageisused
oftentotrain
studentsinthe
classroom.BASIC
isalsousedby
nonprogramming
people,suchas
engineers,whofind
itusefulinproblem
Figure7:ExampleBasicProgramtoAverageNumbers
solving.Formany
years,BASICwaslookeddownonby"realprogrammers,"whocomplainedthatithadtoomany
limitationsandwasnotsuitableforcomplextasks.Newerversions,suchasMicrosoft's
QuickBASIC,includesubstantialimprovements.AnexampleofaBASICprogramanditsoutput
areshowninFigure7.
Pascal:TheLanguageofSimplicity
NamedforBlaisePascal,theseventeenthcenturyFrenchmathematician,Pascalwasdevelopedas
ateachinglanguagebyaSwisscomputerscientist,NiklausWirth,andfirstbecameavailablein
1971.Sincethattimeithasbecomequitepopular,firstinEuropeandnowintheUnitedStates,
particularlyinuniversitiesandcollegesofferingcomputerscienceprograms.

http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

16/17

5/1/2016

ComputerProgramming

TheforemostfeatureofPascalisthatitissimplerthanotherlanguagesithasfewerfeaturesandis
lesswordythanmost.InadditiontothepopularityofPascalincollegecomputerscience
departments,thelanguagehasalsomadelargeinroadsinthepersonalcomputermarketasasimple
yetsophisticatedalternativetoBASIC.Overtheyearsnewversionshaveimprovedontheoriginal
capabilitiesofPascal.Today,Borland'sTurboPascalleadsthePascalworldbecauseitsdesigners
eliminatedmostofthedrawbacksoftheoriginalPascal.TurboPascalisusedbythebusiness
communityandisoftenthechoiceofnonprofessionalprogrammerswhoneedtowritetheirown
programs.
Ada:NamedfortheCountess
Isanysoftwareworthover$25billion?Notanymore,accordingtoDefenseDepartmentexperts.
In1974theU.S.DepartmentofDefensehadspentthatamountonallkindsofsoftwarefora
hodgepodgeoflanguagesforitsneeds.Theanswertothisproblemturnedouttobeanew
languagecalledAdanamedforCountessAdaLovelace,"thefirstprogrammer"(seeAppendixB).
SponsoredbythePentagon,Adawasoriginallyintendedtobeastandardlanguageforweapons
systems,butithasalsobeenusedsuccessfullyforcommercialapplications.Introducedin1980,
Adahasthesupportnotonlyofthedefenseestablishmentbutalsoofsuchindustryheavyweights
asIBMandIntel,andAdaisevenavailableforsomepersonalcomputers.Althoughsomeexperts
havesaidAdaistoocomplex,otherssaythatitiseasytolearnandthatitwillincrease
productivity.Indeed,someexpertsbelievethatitisbyfarasuperiorcommerciallanguagetosuch
standbysasCOBOLandFORTRAN.
WidespreaduseofAdaisconsideredunlikelybymanyexperts.Althoughtherearemanyreasons
forthis(themilitaryservices,forinstance,havedifferentlevelsofenthusiasmforit),probablyits
sizewhichmayhinderitsuseonpersonalcomputersandcomplexityarethegreatestbarriers.
AlthoughtheDepartmentofDefenseisamarketinitself,Adahasnotcaughtontotheextentthat
PascalandChave,especiallyinthebusinesscommunity.
C,C++,Java,andJavascript
AlanguageinventedbyDennisRitchieatBellLabsin1972,Cproducescodethatapproaches
assemblylanguageinefficiencywhilestillofferinghighlevellanguagefeatures.Cwasoriginally
designedtowritesystemssoftwarebutisnowconsideredageneralpurposelanguage.Ccontains
someofthebestfeaturesfromotherlanguages,includingPascal.Ccompilersaresimpleand
compact.Akeyattractionisthatitisindependentofthearchitectureofanyparticularmachine,a
factthatcontributestotheportabilityofCprograms.Thatis,aCprogramcanberunonmorethan
onetypeofcomputerafterithasbeencompiledforthatmachine.
AlthoughCissimpleandelegant,itisnotsimpletolearn.Itwasdevelopedforgifted
programmers,andthelearningcurvemaybesteep.Straightforwardtasksmaybesolvedeasilyin
C,butcomplexproblemsrequiremasteryofthelanguage.
AninterestingsidenoteisthattheavailabilityofConpersonalcomputershasgreatlyenhanced
thevalueofpersonalcomputersforbuddingsoftwareentrepreneurs.Acottagesoftwareindustry
canusethesamebasictoolthelanguageCusedbyestablishedsoftwarecompaniessuchas
MicrosoftandBorland.TodayCishasbeenreplacedbyitsenhancedcousin,C++.C++inturnis
beingchallengedbywebawarelanguageslikeJavaandJavascript,thatlookandactalotlike
C++,butaddfeaturestosupportworkingwithnetworkedcomputers,amongotherthings.

http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

17/17

Оценить