FundamentalProgrammingPrinciples:VariablesandDataTypes
BeyondtheMouseGEOS436/636
JeffFreymueller,Sep5,2017
“TheUncomfortableTruthsWell”,hQp://xkcd.com/568(April13,2009)
Today’sSchedule
• Howdoescomputerprogrammingwork– Whatisaprogramminglanguage?– Whatisaprogram?
• VariablesandDataTypes– Howdowestorevaluesofdifferentkinds?
• Numbers• Stringsoftext• Morecomplicatedthings(likeimages,forexample)
Definiaons
• Aprogramminglanguageisanunambiguousaraficiallanguagethatismadeupofasetofsymbols(vocabulary)andgrammaacalrules(syntax)toinstructamachine.
• Aprogramisasetofinstrucaonsinoneormulapleprogramminglanguagesthatspecifiesthebehaviorofamachine.
• Compila.onorinterpreta.onistheverificaaonofaprogramanditstranslaaonintomachinereadableinstrucaonsofaspecificplaborm.
WhatLanguageDoestheCPUUnderstand?
• TheCPU(CentralProcessingUnit)actuallyunderstandsonlyalanguagecomposedenarelyofnumbers,likethis:– “157655302277854”(thisisamade-upexample)– Thismeans“executeinstrucaon#157usinganargument65530,thenexecuteinstrucaon#22,thenexecuteinstrucaon#77usinganargument854”
– Thelanguagedefiniaontellsthemachinethatinstrucaon#157takesoneargument,but#22doesnot.
• Itispossibleforapersontowritecodeinthismachinelanguage,butalmostnobodydoesitanymorebecauseitissoinconvenient.
IActuallyDidThis
ProgrammingLanguages
• Canbebrokenintotwolargefamilies:• Interpretedlanguages.Aninterpreterprogramtakesincommands,checksyntaxandtranslatestomachinelanguageatruname(e.g.,Matlab,UnixShell)
• Compiledlanguages.Programsaretranslatedandsavedinmachinelanguagebyacompiler.Atrunamenoaddiaonalinterpretaaonisnecessary(e.g.,FORTRAN,C/C++).– Thesegenerallyrunmuchfasterthaninterpretedlanguages
1. Openatexteditor(MATLABeditor,vi,notepad,TextWrangler,…notMSWord)
2. translateyour(physicalormental)flowchartintoasetofinstrucaonsaccordingtotherulesofaprogramminglanguage
3. testyourprogramforsyntacacalcorrectness(asktheinterpreter/compiler)4. iferrors,fixthemandgobackto(3)5. testyourprogramforsemanacerrors(the“fun”part!)6. iferrors,fixthemandgobackto(3)
Now,HowDoesProgrammingWork?
Example:HelloWorld
TheMATLABEditorHelpsYou
TheMATLABEditorHelpsYou
TheMATLABEditorHelpsYou
WhatisaVariable?
• DonaldKnuth:Aquanatythatmaypossessdifferentvaluesasaprogramisbeingexecuted.
• MehranSahami:Aboxinwhichwestuffthings–i.e.aboxwithvariablecontent.
• Wikipedia:Userdefinedkeywordthatislinkedtoavaluestoredincomputer’smemory(runame).
• Theconceptofavariableconsistsof:– Name– Type– Value
Variables:Name• USEMEANINGFULNAMES!• Mustfollowprogramminglanguagerules– MATLABvariablenamesmustbeginwithaleQer,followedbyanycombinaaonofleQers,digits,andunderscores.MATLABdisanguishesbetweenuppercaseandlowercase.Noreservedkeywords!
• USEMEANINGFULNAMES,i.e.namesthatspeak:‘lengthGlacier’or‘glacier_length’NOTNOTNOT‘a’–avoidambiguity
• useconsistentformaqng,i.e.:‘my_cool_var’or‘myCoolVar’–thisiseasiertoread
• agazillionstyleguidesexist–punchline:usemeaningfulnames,beconsistent(that’shardenough)!
Variables:Type
• Whatisatype?–Thinkofsetsofnumbersinmath:N,R,Z,...Thetypereferstohownumbersarebeingrepresentedinacomputer’smemory,i.e.whichbithaswhichmeaning,andhowmanybitsarenecessary
• primiave,builtintypes–forMATLABe.g.:‘int32’,‘double’,‘boolean’(importantfor*printf funcaons)
• complex,homemadetypes–(arrays,)structs,cellarrays(Matlab),classes
Variables:TypeandTypeConversion
• somelanguages,e.g.MATLAB,shells,Perlareweaklytyped:theydoautomaactypeconversions(onetypecanbetreatedasanother)– thisisniceatfirst,occasionallythisleadstonasty/hardtofindproblems(e.g.stringinterpretedasnumber,etc.)
• Otherlanguagesareverypickyandwilltellyouthatyoucan’taddarealnumbertoacomplexnumberwithoutexplicitlyconverang.– Why?Itcanproducemoreefficientmachinecode.– Pickyvslooseisadesigndecision
Variables:Value
• Avalueofthetypeofthevariable:42,3.1415926...,false,‘textstring’,i.e.,thethingwestuffinthebox
• Valuescan/shouldchangeduringtherunameoftheprogram.Somelanguages(notMATLAB)allowyoutodefineanamedconstant,forvaluesthatcan’tchange.
• Weneedtobeabletoassignvaluestovariables,andalsoaccess(dereference)thevalues.
AssignmentandAccess
• Assignment:setthevalueofavariable– MATLAB:num_glaciers = 105– tcshscripang:set filename = “12jun30dena.dat”
• Access:getthevalueofavariable– MATLAB:disp( num2str(num_glaciers) )– tcshscripang:echo $filename
• Whatdoesthisdo?(MATLAB)– num_glaciers = num_glaciers + 1
MATLABTreatsEverythingasaMatrix
• Arraysormatricesarelists,vectors,matricesofdata(1tondimensional)
• Thereforeinsteadofonevaluetheyholdalistofvalueslinkedtoachunkofmemory(asequenceofboxes)
• Accessbyindexnumber:glaciers(5), cov(3,2)
• Shellsallowonlyvectors(1-Darrays).
ExampleArrays• Anumericarray:
• Valuescanbeamixofintegers,realandcomplexnumbers.>> foo = [1; 2; 3+i; 4]
foo = 1.0000 2.0000 3.0000 + 1.0000i 4.0000 • Youcanbrowsethesevaluesinthevariablebrowserwithin
theMATLABGUI.
Index 1 2 3 4 5 6 7 8 9 10
Value 0 -3.2 1000 NaN 1 5 -90 9999 3.141 0
ExampleArrays• Astringarray:
• Examplesofassigningandaccessingstrings:>> foo = ‘Hello Work’>> foo(4)ans =
‘l’ >> foo(1)ans =
‘H’ >> foo(1) + 1ans =
73
Index 1 2 3 4 5 6 7 8 9 10
Value H e l l o W o r k
Whatisgoingonhere!?
Anexample
Jeff0:101:00Noway,José!
HowtoMaketheTable
TheImportanceofPlayingAround• Youwilllearnmoreifyouspendameplayingaroundwiththecomputer,tryingtomakeitdosomethinginteresangtoyou.
• Youcanstartwiththeexercises,typingthemfromthelecturenotesorevendoingacopyandpaste– Youdohavetowatchoutforapostrophes:thestraightapostropheandthecurlyones(‘’)areactuallydifferentcharacters!
– Wordprocessorstoday“help”youbyautomaacallymakingcurlyapostrophesandquotaaonmarksbecauseitlooksfancier.