0% found this document useful (0 votes)
271 views5 pages

Pseudocode: Goal: Practice Writing Pseudocode and Understand How Pseudocode Translates To Real Code

Pseudocode is code written for human understanding rather than for a compiler. It allows programmers to plan algorithms at a high level before writing actual code. Pseudocode is not language-specific, so it can be translated to many programming languages. Writing detailed pseudocode is important for planning complex algorithms and makes it easier to implement the algorithm in real code. Pseudocode style depends on personal preference and the problem being solved, but it should clearly outline the steps of the algorithm.

Uploaded by

Mwai Janna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
271 views5 pages

Pseudocode: Goal: Practice Writing Pseudocode and Understand How Pseudocode Translates To Real Code

Pseudocode is code written for human understanding rather than for a compiler. It allows programmers to plan algorithms at a high level before writing actual code. Pseudocode is not language-specific, so it can be translated to many programming languages. Writing detailed pseudocode is important for planning complex algorithms and makes it easier to implement the algorithm in real code. Pseudocode style depends on personal preference and the problem being solved, but it should clearly outline the steps of the algorithm.

Uploaded by

Mwai Janna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Pseudocode

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.

You might also like