introduction to c++ general rules, conventions and styles · introduction to c++ general rules,...
TRANSCRIPT
IntroductiontoC++GeneralRules,ConventionsandStyles
CS16:SolvingProblemswithComputersILecture#2
ZiadMatni
Dept.ofComputerScience,UCSB
Administrative
• ThisclassiscurrentlyFULLandthewaitlistisCLOSED– Willnotbeaddinganyoneelse Pleasedonotaskagain
• Lab#1andsubmit.csissues
• Homework#1andworkingonGauchoSpace
• Reminder:Don’tleaveyourvaluablesbehindinthelab(orclass)!
4/5/18 Matni,CS16,Sp18 2
LectureOutline
• BasicRulesandConventionsofC++
• VariablesandAssignments
• DataTypesandExpressions
• InputandOutput
4/5/18 Matni,CS16,Sp18 3
4/5/18 Matni,CS16,Sp18 4
1-4: Programstart5: Variabledeclaration6-20: Statements21-22: Programend
cout<<“somestringoranother”; //outputstreamstatement
cin>>some_variable; //inputstreamstatement
coutandcinareobjectsdefinedinthelibraryiostream
Notetheuseofta
bbedsp
aces
What’sTheDifference???
4/5/18 Matni,CS16,Sp18 5
#include<iostream>usingnamespacestd;intmain(){intn=5;while(n<10){ cout<<n; n=n+1;}
return0;}
#include<iostream>usingnamespacestd;intmain(){intn=5;while(n<10){cout<<n;n=n+1;}return0;}
Acompilerprogramcanreadeitherone!ButwhichonecanYOUreadbetter?!?!J
ProgramStyle
• Thelayoutofaprogramisdesignedmainlytomakeitreadablebyhumans
• C++Compilersacceptalmostanypatternsoflinebreaksandindentations!– Solayoutconventionsaretherenotforthemachine,butforthehuman– Conventionvs.Rules–what’sthedifference??
• Conventionshavebeenestablished,forexample:1. Placeopeningbrace‘{‘andclosingbrace‘}’onalinebythemselves2. Useindentedstatements(i.e.usetabbedspaces)3. Useonlyonestatementperline
4/5/18 Matni,CS16,Sp18 6
Wewillcheckforthisconventionuseinyour
labassignments!
SomeC++RulesandConventions
• Variablesaredeclaredbeforetheyareused– Typicallyatthebeginningofprogram
• Statements(notalwayslines)endwithasemi-colon;
• Usecurly-brackets{…} toencapsulategroupsofstatementsthatbelongtogether– Parentheses(…)haveadifferentuseinC++– Asdosquarebrackets[…]– Theyarenotinterchangeable!
4/5/18 Matni,CS16,Sp18 7
Breakingtheserulesisconsideredasyntaxerror:yourprogramwon’tcompile!
SomeC++RulesandConventions
• Includedirectives(like#include<iostream>)arealwaysplacedinthebeginningoftheprogrambeforeanycode– Tellsthecompilerwheretofindinformationaboutobjectsusedintheprogram
• usingnamespacestd;– Tellsthecompilertousenamesofobjectsiniostreamina“standard”way
• mainfunctionsendwitha“return0;”statement– Youshouldalwayshavethis–althoughit’saconvention,notastrictrule
4/5/18 Matni,CS16,Sp18 8
Reminder:WhatareVariables
• Avariableisasymbolicreferencetodata
• Thevariable'snamerepresentswhatinformationitcontains
• Theyarecalled“variables”becausethedatacanchangewhiletheoperationsonthevariableremainthesame
• Ifvariablesareofthesametype, youcanperformoperationsonthem
94/5/18 Matni,CS16,Sp18
VariablesinC++
• InC++,variablesareplaceholdersformemorylocationsintheCPU
• Wecanassignavaluetothem• Wecanchangethatvaluestored• BUTwecannoterasethememorylocationofthatparticular
variable
4/5/18 Matni,CS16,Sp18 10
TypesofC++Variables:General• Thereare3propertiestoavariable:
Variableshaveaname(identifier),atype,andavalueattachedtothem
• Integers– Wholenumbers– Example:122,53,-47
• FloatingPoint– Numberswithdecimalpoints– Example:122.5,53.001,-47.201
• Boolean– Takesononeoftwovalues:
“true”or“false”
• Character– Asinglealphanumeric– Example:“c”,“H”,“%”
• Notetheuseofquotationmarks
• String– Astringofcharacters– Example:“baby”,“whatthe!@$?”
• Notetheuseofquotationmarks
11
There are many other types of variables – you also make your own types! 4/5/18 Matni,CS16,Sp18
AboutVariableNames
• Goodvariablename:indicateswhatdataisstoredinsideit– Agoodvariablenameisa“noun”or“nounphrase”,e.g.:FirstName– Agoodfunctionnameisa“verb”or“verbphrase”,e.g.:SortNumbers()
• Theyshouldmakesensetoanoncomputerprogrammer– Avoidgenericnames,like“var1”or“x”
• Example: name=“BobRoberts” isnotdescriptiveenough,but candidate_name=“BobRoberts” isbetter
124/5/18 Matni,CS16,Sp18
Wewillcheckforthisconventionuseinyour
labassignments!
VariableNameRulesinC++
VariablenamesinC++mustadheretocertainrules.
• TheyMUSTstartwitheitheraletteroranunderscore(_) • Theycannotstartwithanumber• Therestoftheletterscanbealphanumericsorunderscores.• Theycannotcontainspacesordotsorothersymbols
• WhichoftheseisalegalvariablenameinC++4MyBae _StopCondition MyLittlePony_007 James.Bond
134/5/18 Matni,CS16,Sp18
Breakingtheserulesisconsideredasyntaxerror:yourprogramwon’tcompile!
VariableNameCasingWhennamingvariables,functions,etc…
• SnakeCase: Usingunderscorecharacter(‘_’)– Example:mortgage_amount function_fun()– AssociatedwithC,C++programmers
• CamelCase: Usingupper-caseletterstoseparatewords– Example: MortgageAmount FunctionFun()– AssociatedwithJavaprogrammers
• Forthisclass,YOUCANUSEEITHER!ButPICKONEANDBECONSISTENT!!!
4/5/18 Matni,CS16,Sp18 14
Wewillcheckforthisconventionuseinyour
labassignments!
ReservedKeywords
• UsedforspecificpurposesbyC++• MustbeusedastheyaredefinedinC++• CannotbeusedasidentifiersEXAMPLE:Youcannotcallavariable“int”or“else”ForalistofallC++keywords,see:http://en.cppreference.com/w/cpp/keyword
4/5/18 Matni,CS16,Sp18 15
Breakingtheserulesisconsideredasyntaxerror:yourprogramwon’tcompile!
OtherStylingConventions
• Comments:Musthavethem– InC++,use//foronelineatatime,or/*…*/formultiplelines
• TabbingandBraces:– Codeinsideofmain()mustbetabbedappropriately• Evenone-linerif-statements
– Openandclosecurlybraces{…}onnewlines andalignthemwiththeblock
4/5/18 Matni,CS16,Sp18 16
Wewillcheckforthisconventionuseinyour
labassignments!
ExampleofGoodStylingintmain(){
//Getuserinputonnumberofpeople//Thendetermineifthereisroomforthemintmax_capacity(100),num_people;cout<<“Enternumberofpeople:”;cin>>num_people;if(num_people>max_capacity){ cout<<“Toomanypeople!Byacountof”; cout<<num_people–max_capacity;}else{ cout<<“Ok!”;}return0;
}
DeclaringVariables
• VariablesinC++mustbedeclared___________theyareused!Declarationsyntax:Type_nameVariable_1,Variable_2,...;
Examples:doubleaverage,m_score,total_score;intid_num,height,weight,age,shoesize;intpoints;
4/5/18 Matni,CS16,Sp18 18
before
Initializing/AssigningVariableValues
• Whenyoudeclareavariable,it’snotcreatedwithanyvalueinparticular
• Itisgoodpracticetoinitializevariablesbeforeusingthem– Otherwisetheywillcontainwhatevervalueisinthatmemorylocation
• Donotdeclarevariablesinsideloops!!!EXAMPLE:
intnum,doz;num=5;sum(5);doz=num+7;
4/5/18 Matni,CS16,Sp18 19
numisinitializedto5
andsoissum
dozisinitializedto(num+7)
Using=or()forassignmentofdeclaredvaluesisuptoyou!
Assignmentvs.AlgebraicStatements
• C++syntaxisNOTthesameasinAlgebraEXAMPLE:
number=number+3InC++,itmeans:– takethecurrentvalueof“number”,– add3toit,– thenreassignthatnewvaluetothevariable“number”
4/5/18 Matni,CS16,Sp18 20
C++shortcut:number+=3Alsoworkswith:
-=*=/=%=etc…
VariableComparisons
• Whenvariablesarebeingcomparedtooneanother,weusedifferentsymbols
• aisequaltob a==b• aisnotequaltob a!=b• aislargerthanb a>b• aislargerthanorequaltob a>=b• aissmallerthatb a<b• aissmallerthanorequaltob a<=b
Note:Theoutcomeofthesecomparisonsarealwayseithertrueorfalsei.e.BooleanBooleanvariables:false =0true ≠0(notethelower-case)
4/5/18 Matni,CS16,Sp18
VariableTypesinC++1.Integers
int:Basicinteger(wholenumbers,positiveORnegative)• Usually32or64bitswide– So,ifit’s32bitswide,therangeis-231to+231-1Whichis:-2,147,483,648to+2,147,483,647
• Youcanexpressevenlarger(+veand–ve)integersusing: longintandlonglongint
• Youcanexpressonlypositiveintegers(andthusgetalonger+verange)using: unsignedint
4/5/18 Matni,CS16,Sp18 22
VariableTypesinC++2.Real(rational)numbers
double:Realnumbers,positiveORnegativeTypedoublecanbewrittenintwoways:• Simpleformmustincludeadecimalpoint– Examples:34.1,23.0034,1.0,-89.9
• Alternateform:FloatingPointNotation(ScientificNotation)– 3.41e1 means34.1– 3.67e17 means367000000000000000.0 (17digitsafter“3”)– 5.89e-6 means0.00000589 (6decimalplacesbefore“5”)
• Numberleftofe(forexponent)doesnotrequireadecimalpoint• Theexponentcannotcontainadecimalpoint
4/5/18 Matni,CS16,Sp18 23
VariableTypesinC++3.Characters
char:singlecharacter• Canbeanysinglecharacterfromthekeyboard• Todeclareavariableoftypechar:
charletter;
• Characterconstantsareenclosedinsinglequotescharletter='a';
4/5/18 Matni,CS16,Sp18 24
VariableTypesinC++4.Strings
string:acollectionofcharacters(astringofcharacters)• stringisaclass,differentfromtheprimitivedatatypesdiscussedsofar.
– We’lldiscussclassesfurtherinthecourse
• UsingC++stringsrequiresyoutoincludethe“string”module:#include<string>
• Todeclareavariableoftypestring:stringname=“HomerSimpson”;
• Thereare“older”typesofstringscalledC-StringsthatarestillinuseinC++– Moreonthoselater…
4/5/18 Matni,CS16,Sp18 25
Noteon‘vs“• Singlequotesareonlyusedforchartypes• Doublequotesareonlyusedforstringtypes
• So,whichoftheseisokandwhichisn’t?charletter1=“a”;charletter2=‘b’;stringtown1=“Mayberry”;stringtown2=‘Xanadu’;
4/5/18 Matni,CS16,Sp18 26
TypeCompatibilities
• GeneralRule:Youcannotoperateondifferentlytypedvariables.– Exceptwithintanddoubletypes
– Justlikeinmostcomputerlanguages
• So,if: then:intmy_var=2; my_var+my_char isasyntaxerror
charmy_char=‘x’;
• Thereareruleswithoperationsbetweenintanddouble…
4/5/18 Matni,CS16,Sp18 27
intßàdouble• Variablesoftypedoubleshouldnotbeassignedtovariablesoftypeint
• Variableoftypeint,however,cannormallybestoredinvariablesoftypedouble
EXAMPLE: doublenumero; numero=2;
• numerowillcontain2.0000(unfixednumberofplacesafterdecimalpt)
EXAMPLE: intnumero; numero=2.789;
• numerowillcontain2
4/5/18 Matni,CS16,Sp18 28
intßàdouble
4/5/18 Matni,CS16,Sp18 29
So,whathappenswithvariablezhere?intx(9);doubley(4),z;z=x/y;cout<<z;
Thisprintsout:2.25
So,whathappenswithvariablephere?intn(4);doublem(9),p;p=m/n;cout<<p;
Thisprintsout:2.25
Ifoneorbothoperandsaredouble,theresultisdouble
So,whathappenswithvariablechere?inta(9),b(4);doublec;c=a/b;cout<<c;
Thisprintsout:2
VariableTypesinC++5.Booleans
bool:abinaryvalueofeither“true”(1)or“false”(0).• YoucanperformLOGICALoperationsonthistype:– || LogicalOR– && LogicalAND
Also,whendoingcomparisons,theresultisaBooleantype.EXAMPLE:Whatwillthisprintout?? inta=44,b=9; boolc; c=(a==b); cout<<c;
4/5/18 Matni,CS16,Sp18 30
Ans:0
ArithmeticExpressions
• Precedencerulesforoperatorsarethesameaswhatyouusedinyouralgebraclasses– EXAMPLE:x+y*z (yismultipliedbyzfirst)
• Useparenthesestoforcetheorderofoperations(recommended)– EXAMPLE:(x+y)*z (xandyareaddedfirst)
4/5/18 Matni,CS16,Sp18 31
OperatorShorthands
• SomeexpressionsoccursooftenthatC++containsshorthandoperatorsforthem
• Allarithmeticoperatorscanbeusedthisway:
– count=count+2; ---canbewrittenas---count+=2;– bonus=bonus*2; ---canbewrittenas---bonus*=2;– time=time/factor; ---canbewrittenas---time/=factor;– remainder=remainder%(cnt1+cnt2);
---canbewrittenas---remainder%=(cnt1+cnt2);
4/5/18 Matni,CS16,Sp18 32
ReviewofBooleanExpressions:AND,OR,NOT
ANDoperator &&• (expression1)&&(expression2)• Trueifbothexpressionsaretrue
ORoperator ||• (expression1)||(expression2)• Trueifeitherexpressionistrue
NOToperator !• !(expression)• False,iftheexpressionisTrue(andviceversa)
Note:nospacebetweeneach‘|’character!
TruthTablesforBooleanOperations
4/5/18 Matni,CS16,Sp18 34
X Y X&&YF FF TT FT T
X Y X||YF FF TT FT T
FFFT
FTTT
X !XFT
TF
AND OR NOT
4.ANDandORarecommutative,butnotwhenmixed(so,ordermatters)X&&Y=Y&&XX&&(Y||Z)isnotthesameas(X&&Y)||Z
IMPORTANTNOTES:1.ANDandORarenotoppositesofeachother!!2.AND:ifjustoneconditionisfalse,thentheoutcomeisfalse3.OR:ifatleastoneconditionistrue,thentheoutcomeistrue
PrecedenceRulesonOperationsinC++
4/5/18 Matni,CS16,Sp18 35
• IfparenthesisareomittedfromC++expressions,thedefaultprecedenceofoperationsis:
YOURTO-DOs
q FinishLab1byMondayq DoHW2byTuesdayq VisitProf’sandTAs‘officehoursifyouneedhelp!
Ø Prof.’shoursareMONDAYfrom11AMto12PM(orbyappointment!)
q Reverseglobalwarmingq Bonuspointsforendingworldhunger
4/6/18 Matni,CS16,Sp18 36
4/6/18 Matni,CS16,Sp18 37