Beruflich Dokumente
Kultur Dokumente
Pseudocodeiscodewrittenforhumanunderstandingnotacompiler.Youcanthinkof
pseudocodeasenglishcode,codethatcanbeunderstoodbyanyone(notjustacomputer
scientist).Pseudocodeisnotlanguagespecific,whichmeansthatgivenablockofpseudocode,
youcouldconvertittoJava,Python,C++,orwhateverlanguageyousodesire.
Letustellyounow,pseudocodewillbeimportanttoyourfutureinComputerScience.Typically
pseudocodeisusedtowriteahighleveloutlineofanalgorithm.Asyoumayalreadyknow,an
algorithmisaseriesofstepsthataprogramtakestocompleteaspecifictask.Thealgorithms
youmay(andwill)beaskedtowritecangetverycomplicatedwithoutadetailedplan,sowriting
pseudocodebeforeactuallycodingwillbeverybeneficial.
Goal:Practicewritingpseudocodeandunderstandhowpseudocodetranslatestorealcode.
HowtoWritePseudocode
Therearenoconcreterulesthatdictatehowtowritepseudocode,however,therearecommonly
acceptedstandards.Areadershouldbeabletofollowthepseudocodeandhandsimulate(run
throughthecodeusingpaperandpencil)whatisgoingtohappenateachstep.Afterwriting
pseudocode,youshouldbeabletoeasilyconvertyourpseudocodeintoanyprogramming
languageyoulike.
Weuseindentationtodelineateblocksofcode,soitisclearwhichlinesareinsideofwhich
method,loop,etc.Indentationiscrucialtowritingpseudocode.Javamaynotcareifyoudon't
indentinsideyourifstatements,butahumanreaderwouldbecompletelylostwithoutindentation
cues.Remember:Humancomprehensionisthewholepointofpseudocode.
So,whatdoespseudocodelooklike?Consideranalgorithmtocompleteyourmathhomework.
Belowweveincludedexamplesofbothgoodandbadpseudocode.
GoodPseudocode
RealCode(inJava)
BadPseudocode
methoddoMathHomework():
Getpencil
Opentextbookandnotebook
Gothroughalltheproblems:
Completeproblem
whiletheproblemis
wrong:
Tryagain
Cleanupyourdesk
Submityourhomework
publicvoiddoMathHomework(){
this.getPencil()
_textBk.open()
_noteBk.open()
for(inti=0i<_problems.length()i++){
_problems[i].solve()
while(!_problems[i].isRight()){
this.eraseSolution(i)
_problems[i].solve()
this.cleanDesk()
this.submit()
}
methoddoMathHomework():
Getthingsforhomework
Dotheproblemscorrectly
Finishthehomework
IfwewereprovidedthebadpseudocodeandaskedtoconvertitintoJava,wewouldhaveto
putalotofthoughtintoeachlineinordertoconvertit,whichdefeatstheoriginalpurposeof
writingit.Whenreadingthebadpseudocode,areadermight(should)wonder,whatthingsdoI
needtodohomework?orhowdoIdomyhomeworkcorrectly?thisisagoodindicatorthat
yourpseudocodeisntspecificenough.
Thegoodpseudocodeisdetailedenoughthatinordertoconvertitintocode,wesimplyhadto
readlinebylineandturnitintocode.However,youllnoticethateverylineisnotina1:1ratio
withrealcode.Forexample,Tryagainisactuallyimplementedasthis.eraseSolution(i)
problems[i].solve().Becausethiswasasmallandsimpleimplementationdetail,wecouldomit
itinthepseudocodeforthesakeofseeingthebiggerpicture.Thatsaid,themorespecificyour
pseudocodeis,themoreusefulitwillbewhenyouhavetotranslateitintocodegoingtoo
highlevelwillleaveyouwithpseudocodelikethebadexample.
Also,itsnoteworthythatalthoughIchosetoconvertmypseudocodeintoJava,Icouldhavejust
aseasilyconverteditintoPythonorC++rememberthatpseudocodeisnotlanguagespecific
sowearenotlookingforalmostJavacode,butinstead,wearelookingforastrong
understandingofthealgorithmathand.
DifferencesinPseudocodeStyle
Intheexampleabove,thepseudocodewasveryclosetoproseEnglish.Yetwecouldstillsee
howtotranslateitintoobjectorientedcode.Insomecases,however,thepseudocodecould
verymuchresemblecode.Consideranalgorithmthatprintsoutalloddnumbersbetween1and
10:
methodprintOddNumbers():
i=1
whilei<11:
ifiisnotdivisibleby2:
printi
i++
Thispseudocodestylewasmuchmoreappropriateforthegivenalgorithm,anditwouldntmake
muchsensetohavetriedtomakeitbetterresembleproseEnglish.Pseudocodestyledepends
greatlyonpersonalpreference,theproblemyoureaskedtosolve,andonwhatyou'reoptimizing
for:speed,readability,aesthetics,etc.Asyouwritemorepseudocode,youwilldiscoverwhat
stylecomesmostnaturallytoyou.
Insummary:
Rosesarered,violetsareblue,pseudocodecomesinmanyshapesandsizes,just
makesureitappropriatelyoutlinesthealgorithmyourewriting.
DrawingTurtles
Remembertheturtledemofromlecture?Youaregoingtocreateyourown!Yourturtlecando
thefollowingthings:
moveforwardanumberofsteps(eachstepisonepixellong)
turnleft90degrees
turnright90degrees
putitspendown,whichstartsdrawingtheturtle'spath
liftitspenup,whichstopsdrawingtheturtle'spath
Thewidthoftheturtle'spenisonepixel.Theinitialdirectionoftheturtleisfacingnorth.
CheckPoint1:Pseudocode
Youwillbewritingpseudocodeforanalgorithmthatdirectstheturtletodrawachainof
squaresdecreasinginsizeby10pixels.
Hint:thesidelengthofasquareshouldneverbelessthan0,right?
Example:Thechainshouldlooklikethisforastartinglengthof50:
FillinthefollowingpseudocodemethodinSublimeoranothertexteditor:
/*inputs:
*turtleturtlethatisdrawing
*sqSideLengthinitialsquareslength
*/
methoddrawSqChain(turtle,sqSideLength){
//fillmeinwithpseudocodehere!
}
ShowyourpseudocodetoaTAbeforemovingon.
Nowthatyouhavefinishedwritingyourpseudocode,putyourskillstothetestandgocodeyour
algorithm.Ifyouhavewrittenyourpseudocodewell,itshouldbeatrivialsteptotranslateitlineby
lineintoJava.
CheckPoint2:Coding
Runcs015_installlabPseudocode.Thiswillinstallstencilcodein
/home/<yourlogin>/course/cs015/labPseudocode/.
Openupeclipse,clickApp.javaandclickRunas>>JavaApplication
Whatsthis?!Youshouldnoticethatyourprogramwillnotrun
Continuereadingtoseehowtofixthis.
Ohno!ItappearsthatSpyTurtleshavelockedtheTurtleDrawer,whichispreventingyoufrom
beingabletoexecuteyourcode.IfyouinspectthecodeinMyTurtleDrawer.javayoull
noticethattheprogramcanbeunlockedbysuccessfullypassinginapassword(thatis
dependentonyourusername)tothecheckPassword(Stringusername,String
password)method.DuetothecunningoftheSpyTurtles,ourhumaneyeisunabletoseethe
innerworkingsofthismethod.SothislookslikeajobfortheEclipseDebugger(andyour
superspyabilities).
Yourmission:Unlockthisprogram.
CheckPoint3:MissionImpossible
checkPassword(Stringusername,Stringpassword)worksbyusingyour
logintogenerateapassword.ItthenstoresthisinthevariablecorrectPassword
andcheckswhetheryourinputtedpasswordequalscorrectPassword.
TounlockMyTurtleDraweryouhavetofigureoutwhatthispasswordis!Youcould
trytofigureouthowcheckPassword(...)generatesthepassword,butthisis
prettyhard.
Instead,usetheEclipseDebuggertofindthevalueofcorrectPassword!
(SeeLabDebuggingPart2forarefresherontheDebugger)
Hint:WeshouldusetheDebuggertoseetheinnerworkingsofthemethod.
TheprogramhasbeenunlockedandtheSpyTurtlesplanshavebeenfoiled!Great!Nowlets
actuallygetcoding.
CheckPoint4:ActuallyCoding
FillinthedrawSqChain(Turtleturtle,intsideLength)methodinthe
MyTurtleDrawer.javafile.Lookatthecommentsinthefiletoseewhatmethods
ofTurtleyoucancall.
Note:Youdonotneedtomodifytheotherfile,App.java
Note:TheTurtledrawsfromarandompointonthescreen
Ifyourturtledoesnotdrawasexpected,gobackandhandsimulateyourpseudocode
again!Whatisgoingwrong?
ShowyourprogramtoaTAtogetcheckedofffortodayslab!
Congratulationsonfinishingthelab.Ifyouarefinishedearly,feelfreetoplayaroundwiththe
drawingturtlesandmakesomecooldesigns(maybetryaspiralorafilledinsquare)thisisa
greatwaytopracticewritingloops.