1/28/16
1
C++ Primer Part 1
CMSC 202
Topics Covered • Our first “Hello world” program • Basic program structure • main() • Variables, identifiers, types • Expressions, statements • Operators, precedence, associativity
2
1-3
ASampleC++Program
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
2
Display1.1ASampleC++Program(2of2)
1-4Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-5
C++Variables
• C++IdenGfiers– Keywords/reservedwordsvs.IdenGfiers– Case-sensiGvityandvalidityofidenGfiers– Meaningfulnames!
• Variables– AmemorylocaGontostoredataforaprogram– Mustdeclarealldatabeforeuseinprogram
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Variable Declaration • Syntax: <type> <legal identifier>; • Examples:
int sum; float average; double grade = 98;
– Must be declared before being used – May appear in various places and contexts (described later) – Must be declared of a given type (e.g. int, float, char, etc.)
Semicolon required!
6
1/28/16
3
7
Variable Declarations (con’t)
When we declare a variable, we tell the compiler: • When and where to set aside memory space for
the variable • How much memory to set aside • How to interpret the contents of that memory: the
specified data type • What name we will be referring to that location by:
its identifier
8
Naming Conventions • Naming conventions are rules for names of
variables to improve readability • CMSC 202 has its own standards, described in
detail on the course website Ø Start with a lowercase letter Ø Indicate "word" boundaries with an uppercase letter Ø Restrict the remaining characters to digits and
lowercase letters
topSpeed bankRate1 timeOfArrival
• Note: variable names are case sensitive!
DataTypes:Display1.2SimpleTypes(1of2)
1-9Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
4
DataTypes:Display1.2SimpleTypes(2of2)
1-10Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-11
AssigningData
• IniGalizingdataindeclaraGonstatement– Results"undefined"ifyoudon’t!
• intmyValue=0;
• AssigningdataduringexecuGon– Lvalues(le\-side)&Rvalues(right-side)
• Lvaluesmustbevariables• Rvaluescanbeanyexpression• Example:distance=rate*Gme;Lvalue:"distance"Rvalue:"rate*Gme"
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-12
DataAssignmentRules
• CompaGbilityofDataAssignments– Typemismatches
• GeneralRule:Cannotplacevalueofonetypeintovariableofanothertype
– intVar=2.99; //2isassignedtointVar!• Onlyintegerpart"fits",sothat’sallthatgoes• Called"implicit"or"automaGctypeconversion"
– Literals• 2,5.75,"Z","HelloWorld"• Considered"constants":can’tchangeinprogram
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
5
1-13
EscapeSequences
• "Extend"characterset• Backslash,\precedingacharacter
– Instructscompiler:aspecial"escapecharacter"iscoming
– Followingcharactertreatedas"escapesequencechar"
– Display1.3nextslide
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Display1.3SomeEscapeSequences(1of2)
1-14Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Display1.3SomeEscapeSequences(2of2)
1-15Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
6
1-16
LiteralData
• Literals– Examples:
• 2 //Literalconstantint• 5.75 //Literalconstantdouble• 'Z' //Literalconstantchar• "HelloWorld\n" //Literalconstantstring
• CannotchangevaluesduringexecuGon• Called"literals"becauseyou"literallytyped"theminyourprogram!
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Constants
• Youshouldnotuseliteralconstantsdirectlyinyourcode– Itmightseemobvioustoyou,butnotso:
• “limit=52”:isthisweeksperyear…orcardsinadeck?
• Instead,youshouldusenamedconstants– Representtheconstantwithameaningfulname– AlsoallowsyoutochangemulGpleinstancesinacentralplace
1-17Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Constants
• Therearetwowaystodothis:– Oldway:preprocessordefiniGon:
#define WEEKS_PER_YEAR 52
(Note:thereisno“=“)– Newway:constantvariable:
• Justaddthekeyword“const”tothedeclaraGon
const float PI = 3.14159;
1-18Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
7
1-19
ArithmeGcOperators:Display1.4NamedConstant(1of2)
• StandardArithmeGcOperators– Precedencerules–standardrules
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
ArithmeGcOperators:Display1.4NamedConstant(2of2)
1-20Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Operators,Expressions
• Recall:mostprogramminglanguageshaveavarietyofoperators:calledunary,binary,andeventernary,dependingonthenumberofoperands(thingstheyoperateon)
• Usuallyrepresentedbyspecialsymboliccharacters:e.g.,‘+’foraddiGon,‘*’formulGplicaGon
1-21Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
8
Operators,Expressions
• TherearealsorelaGonaloperators,andBooleanoperators
• Simpleunitsofoperandsandoperatorscombineintolargerunits,accordingtostrictrulesofprecedenceandassocia-vity
• Eachcomputableunit(bothsimpleandlargeraggregates)arecalledexpressions
1-22Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
BinaryOperators
• Whatisabinaryoperator?– Anoperatorthathastwooperands
<operand><operator><operand>
– ArithmeGcOperators+-*/%
– RelaGonalOperators<>==<=>=
– LogicalOperators&&||
23
RelaGonalOperators• InC++,allrelaGonaloperatorsevaluatetoabooleanvalueofeithertrueorfalse. x = 5; y = 6;
x>ywillalwaysevaluatetofalse.
• C++hasaternaryoperator–thegeneralformis:(condiGonalexpression)?truecase:falsecase;
• Ternaryexample:Cout << (( x > y ) ? "X is greater" : "Y is greater");
24
1/28/16
9
UnaryOperators• Unaryoperatorsonlyhaveoneoperand.
!++--
!islogicalnegaGon,!trueisfalse,!falseistrue++and--aretheincrementanddecrementoperatorsx++apost-increment(pos|ix)operaGon++xapre-increment(prefix)operaGon
• ++and--are“shorthand”operators.Moreontheselater…
25
Precedence,AssociaGvity• OrderofoperatorapplicaGontooperands:
• Pos|ixoperators:++--(righttole\)• Unaryoperators:+-++--!(righttole\)• */%(le\toright)• +-(le\toright)• <><=>=• ==!=• &&• ||• ?:• Assignmentoperator:=(righttole\)
26
AssociaGvity
• Whatisthevalueoftheexpression?3*6/9(3*6)/918/92
• Whataboutthisone?intx,y,z;x=y=z=0;
1-27Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
10
1-28
ArithmeGcPrecision
• PrecisionofCalculaGons– VERYimportantconsideraGon!
• ExpressionsinC++mightnotevaluateasyou’d"expect"!
– "Highest-orderoperand"determinestypeofarithmeGc"precision"performed
– Commonpi|all!
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-29
ArithmeGcPrecisionExamples
• Examples:– 17/5evaluatesto3inC++!
• Bothoperandsareintegers• Integerdivisionisperformed!
– 17.0/5equals3.4inC++!• Highest-orderoperandis"doubletype"• Double"precision"divisionisperformed!
– intintVar1=1,intVar2=2;intVar1/intVar2;
• Performsintegerdivision!• Result:0!
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-30
IndividualArithmeGcPrecision
• CalculaGonsdone"one-by-one"– 1/2/3.0/4performs3separatedivisions.
• Firstà1/2equals0• Thenà0/3.0equals0.0• Thenà0.0/4equals0.0!
• Sonotnecessarilysufficienttochangejust"oneoperand"inalargeexpression– MustkeepinmindallindividualcalculaGonsthatwillbeperformedduringevaluaGon!
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
11
1-31
TypeCasGng
• CasGngforVariables– Canadd".0"toliteralstoforceprecisionarithmeGc,butwhataboutvariables?
• Wecan’tuse"myInt.0"!– staGc_cast<double>intVar – Explicitly"casts"or"converts"intVartodoubletype
• Resultofconversionisthenused• Exampleexpression:doubleVar=staGc_cast<double>intVar1/intVar2;
– CasGngforcesdouble-precisiondivisiontotakeplaceamongtwointegervariables!
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-32
TypeCasGng
• Twotypes– Implicit—alsocalled"AutomaGc"
• DoneFORyou,automaGcally17/5.5Thisexpressioncausesan"implicittypecast"totakeplace,casGngthe17à17.0
– Explicittypeconversion• ProgrammerspecifiesconversionwithcastoperatorstaGc_cast<double>17/5.5
Sameexpressionasabove,usingexplicitcaststaGc_cast<double>myInt/myDouble
Moretypicaluse;castoperatoronvariable
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-33
ShorthandOperators
• Increment&DecrementOperators– Justshort-handnotaGon– Incrementoperator,++intVar++;isequivalenttointVar=intVar+1;
– Decrementoperator,--intVar--;isequivalenttointVar=intVar–1;
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
12
1-34
ShorthandOperators:TwoOpGons
• Post-IncrementintVar++– Usescurrentvalueofvariable,THENincrementsit
• Pre-Increment++intVar– Incrementsvariablefirst,THENusesnewvalue
• "Use"isdefinedaswhatever"context"variableiscurrentlyin
• Nodifferenceif"alone"instatement:intVar++;and++intVar;àidenGcalresult
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-35
Post-IncrementinAcGon
• Post-IncrementinExpressions:int n=2,
valueProduced;valueProduced=2*(n++);cout<<valueProduced<<endl;cout<<n<<endl;– Thiscodesegmentproducestheoutput:43
– Sincepost-incrementwasused
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-36
Pre-IncrementinAcGon
• NowusingPre-increment:int n=2,
valueProduced;valueProduced=2*(++n);cout<<valueProduced<<endl;cout<<n<<endl;– Thiscodesegmentproducestheoutput:63
– Becausepre-incrementwasused
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
13
1-37
AssigningData:ShorthandNotaGons
• Display,page14
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-38
ConsoleInput/Output
• I/Oobjectscin,cout,cerr• DefinedintheC++librarycalled<iostream>
• Musthavetheselines(calledpre-processordirecGves)nearstartoffile:– #include<iostream>usingnamespacestd;
– TellsC++touseappropriatelibrarysowecanusetheI/Oobjectscin,cout,cerr
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-39
ConsoleOutput
• Whatcanbeoutpu�ed?– Anydatacanbeoutpu�edtodisplayscreen
• Variables• Constants• Literals• Expressions(whichcanincludeallofabove)
– cout<<numberOfGames<<"gamesplayed.";2valuesareoutpu�ed:
"value"ofvariablenumberOfGames,literalstring"gamesplayed."
• Cascading:mulGplevaluesinonecout
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
14
1-40
SeparaGngLinesofOutput
• Newlinesinoutput– Recall:"\n"isescapesequenceforthechar"newline"
• Asecondmethod:objectendl
• Examples:cout<<"HelloWorld\n";
• Sendsstring"HelloWorld"todisplay,&escapesequence"\n",skippingtonextline
cout<<"HelloWorld"<<endl;• Sameresultasabove
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Forma�ngOutput
• Forma�ngnumericvaluesforoutput– Valuesmaynotdisplayasexpected cout << "The price is $" << price << endl;
• Ifprice(declaredadouble)hasthevalue78.5,youmightget
– Thepriceis$78.5000000– Thepriceis$78.5
• Neitheriswhatyouwant– HavetotellC++howtooutputnumbers.
1-41Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-42
Forma�ngNumbers
• "MagicFormula"toforcedecimalsizes:cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);
• Thesestatementsforceallfuturecout’edvaluestohaveexactlytwodigitsa\erthedecimalplace:– Example:cout<<"Thepriceis$"<<price<<endl;
• Nowresultsinthefollowing:The price is $78.50
• Canmodifyprecision"asyougo"aswell.
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
15
Forma�ngIntegers
• Fieldwidthandfillcharacters– Must#include <iomanip> – setw(n)setsfieldwidthton– cout.fill(c)sets“fill”charactertoc
• Example:int x = 7;
cout.fill('0'); // set fill character to zero
cout << setw(3) << x << endl;
Outputs007 (le\-padswithzeros)
1-43Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
C-strings
• C++hastwodifferentkindsof“stringofcharacters”:– theoriginalC-string:arrayofcharacters– Theobject-orientedstringclass
• C-stringsareterminatedwithanullcharacter(‘\0’)char myString[80];
declaresavariablewithenoughspaceforastringwith79usablecharacters,plusnull.
1-44Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
C-strings
• YoucaniniGalizeaC-stringvariable:charmyString[80]=“Helloworld”;
Thiswillsetthefirst11charactersasgiven,makethe12thcharacter‘\0’,andtherestunusedfornow.
1-45Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
16
Stringtype• C++addedadatatypeof“string”
– NotaprimiGvedatatype;disGncGonwillbemadelater
– Mayneed#include <string> atthetopoftheprogram
– The“+”operatoronstringsconcatenatestwostringstogether
– cin>>strwherestrisastringonlyreadsuptothefirstwhitespacecharacter
1-46Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
StringEquality
• InPython,youcanusethesimple“==“operatortocomparetwostrings:
ifname==“Fred”:• InC++,youcanuse“==“tocomparetwostringclassitems,butnotC-strings!
• TocomparetwoC-strings,youhavetousethefuncGonstrcmp();itisnotsyntacGcallyincorrecttocomparetwoC-stringswith“==“,butitdoesnotdowhatyouexpect…
1-47Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-48
InputUsingcin
• cinforinput,coutforoutput• Differences:
– ">>"(extracGonoperator)pointsopposite• Thinkofitas"poinGngtowardwherethedatagoes"
– Objectname"cin"usedinsteadof"cout"– Noliteralsallowedforcin
• Mustinput"toavariable"
• cin>>num;– Waitson-screenforkeyboardentry– Valueenteredatkeyboardis"assigned"tonum
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
17
1-49
PrompGngforInput:cinandcout
• Always"prompt"userforinputcout<<"Enternumberofdragons:";cin>>numOfDragons;
– Noteno"\n"incout.Prompt"waits"onsamelineforkeyboardinputasfollows:Enternumberofdragons:____
– Underscoreabovedenoteswherekeyboardentryismade
• Everycinshouldhavecoutprompt– Maximizesuser-friendlyinput/output
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Input/Output(1of2)
1-50Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
Input/Output(2of2)
1-51Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
18
1-52
ErrorOutput
• Outputwithcerr– cerrworksalmostthesameascout– ProvidesmechanismfordisGnguishingbetweenregularoutputanderroroutput
• Re-directoutputstreams– Mostsystemsallowcoutandcerrtobe"redirected"tootherdevices
• e.g.,lineprinter,outputfile,errorconsole,etc.
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-53
ProgramStyle• Bo�om-line:Makeprogramseasytoreadandmodify
• Comments,twomethods:– //TwoslashesindicateenGrelineistobeignored– /*Delimitersindicateseverythingbetweenisignored*/– Bothmethodscommonlyused
• IdenGfiernaming– ALL_CAPSforconstants– lowerToUpperforvariables– Mostimportant:MEANINGFULNAMES!
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-54
Libraries
• C++StandardLibraries• #include<Library_Name>
– DirecGveto"add"contentsoflibraryfiletoyourprogram
– Called"preprocessordirecGve"• Executesbeforecompiler,andsimply"copies"libraryfileintoyourprogramfile
• C++hasmanylibraries– Input/output,math,strings,etc.
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
19
1-55
Namespaces• Namespacesdefined:
– CollecGonofnamedefiniGons• Fornow:interestedinnamespace"std"
– HasallstandardlibrarydefiniGonsweneed• Examples:#include<iostream>usingnamespacestd;
• IncludesenGrestandardlibraryofnamedefiniGons
• #include<iostream>usingstd::cin; usingstd::cout;
• Canspecifyjusttheobjectswewant
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-56
Summary1
• C++iscase-sensiGve• Usemeaningfulnames
– Forvariablesandconstants• Variablesmustbedeclaredbeforeuse
– ShouldalsobeiniGalized• UsecareinnumericmanipulaGon
– Precision,parentheses,orderofoperaGons• #includeC++librariesasneeded
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1-57
Summary2
• Objectcout– Usedforconsoleoutput
• Objectcin– Usedforconsoleinput
• Objectcerr– Usedforerrormessages
• Usecommentstoaidunderstandingofyourprogram– Donotovercomment
Copyright©2012PearsonAddison-Wesley.Allrightsreserved.
1/28/16
20
58
UsingtheCCompileratUMBC
• Invokingthecompilerissystemdependent.
– AtUMBC,wehavetwoCcompilersavailable,ccandgcc.
– Forthisclass,wewillusethegcccompilerasitisthecompileravailableontheLinuxsystem.
59
InvokingthegccCompiler
Attheprompt,type
g++ -Wall program.cpp –o program.out
whereprogram.cppistheC++programsourcefile(thecompileralsoaccepts“.cc”asafileextensionforC++source)
• -WallisanopGontoturnonallcompilerwarnings(bestfornewprogrammers).
60
TheResult:a.out
• Iftherearenoerrorsinprogram.cpp,thiscommandproducesanexecutablefile,whichisonethatcanbeexecuted(run).
• Ifyoudonotusethe“-o”opGon,thecompilernamestheexecutablefilea.out.
• Toexecutetheprogram,attheprompt,type ./program.out
• Althoughwecallthisprocess“compilingaprogram,”whatactuallyhappensismorecomplicated.
1/28/16
21
UNIXProgrammingTools
• Wewillbeusingthe“make”systemtoautomatewhatwasshowninthepreviousfewslides
• Thiswillbediscussedinlab
1-61Copyright©2012PearsonAddison-Wesley.Allrightsreserved.