Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Lecture2
C++programingforbeginners
19April2019
Lecturer:Dr.AnleWang&Dr.SergeySukhomlinov
�1
E-mail:[email protected]
Lecture2
• RememberthebasicstructureofaC++program(library,function,variables,statements,return)• NEVERmissapartofcurlybrace{},semicolon;attheendofstatement.• Useindentationandalsomakeitreadable.•
18April2019 �2
Somecommentsofcoding
Lecture2
• Explorebasicdatatypes,basicoperators,declarationofavariable;• Discoverhowtousearithmeticoperations;• Learnsimpleinputandoutputstream(cin,cout,cerr,clog).
• Afterthislecture,youshouldbeableto:✓BefamiliarwiththebasiccomponentsofaC++program;
✓Declarationofavariable,performsimplearithmeticoperationsandinputoroutputwhatyouwant,displayonscreen.
✓Becomefamiliarwiththeusagewithincrementanddecrementoperator.
18April2019 �3
ContentsofLecture2
Lecture219April2019 �4
AdetailedlookatC++codecomments
libraries
functions
• Asimpleprogrammustcontainsomebasiclibrariesandfunctions.Rememberthatmainfunctionisnecessary.
Lecture218April2019 �5
AdetailedlookatC++code
• Lines beginning with a hash sign (#) are directives readand interpreted by preprocessor. They are special linesinterpretedbeforethecompilation.
• For different function, search the internet to findproperlibrary. Here #include <iostream> defines the input andoutputoperationonscreen.
Lecture218April2019 �6
AdetailedlookatC++code
• Themainfunctioniscalledbytheoperatingsystemwhentheprogramstarts.
• AllC++programsmustdefineamainfunction.• Nowwewilllookintomoredetailsinthefunction,such
asvariables,operators,etc.
intmain(){declarevariablesstatementsreturn0;}
• Definevariableasaportionofmemorytostoreavalue.• C++isahigh-typedlanguage,everyvariableneedstohaveatype,definethekindofdatastored.✓C++definesnumbersofbasicdatatypes,suchasint,float,etc.✓TheC++libraryincludesmoretypes.✓Thetypeofavariablecannotbechangesatrun-time.
•Wemustdefineavariablebeforeusingit.
Whatisavariable?
Datatype variables setvaluetovariables
`
�7Lecture218April2019
• Consistofletters,digitsandtheunderscorecharacter(_);• Mustbeginwithaletterorunderscore;• Casesensitive:sum!=SUM• Illegalidentifiers:✓ helloworld(nospacebetweenletters)✓ helloworld!(noexclamation)✓ hello+world(nosymbol)✓ 1helloworld(identifiercannotbeginwithadigit)✓ double,if(keywordtoidentifydatatypes,operators)
Howtonameavariable?
�8Lecture218April2019
• Datatype:setofvaluestogetherwithasetofoperations.• C++datatypes:✓simple.✓structured.✓pointer.• SimpleC++datatypes:✓integral:numberswithdecimal.✓floating-point:decimalnumbers.✓enumeration:user-defineddatatype.✓char:singlecharacter,suchas‘$’.✓booleandatatype:trueorfalse.
Fundamentaldatatypes
�9Lecture218April2019
Fundamentaldatatypes
http://www.cplusplus.com/doc/tutorial/variables/�10Lecture218April2019
• char:Thesmallestintegraldatatype(1byte);• forcharacters:letters,digits,specialsymbols.• Insinglequotes:‘0’,‘#’,‘A’…• Whatis‘’?
• booltype:twovalues(true,false).• manipulateBooleanlogicaloperation.
Fundamentaldatatypes(char,bool)
�11Lecture218April2019
• integralnumberswithoutdecimal(4byte);• Neverusecommainanintegralnumber;• 12,-25697,• Positiveintegersdonotneedtohave+sign.• Findthedifferencebetweenfollowingexpression:2/3,2.0/3,2.0/3.0
Fundamentaldatatypes(int)
�12Lecture218April2019
• decimalnumber,scientificnotationinC++language;• floating-pointdatatype:✓float;(6-7digits)✓double;(12digits)✓longdouble;• maximumdigitsofadecimalnumber.• setprecisionforfloatingdatatype.setprecision
Fundamentaldatatypes(floating-point)
�13Lecture218April2019
• typeidentifier=initial_value;//c-likeinitialization• typeidentifier(initial_value);//structureinitialization• typeidentifier{initial_value}.//uniforminitialization
Declarationandinitializationofavariable
�14Lecture218April2019
Datatype variables setvaluetovariables
• Declareavariablebeforeuseit;• Whenavariableisdeclaredinonefunction,thevariablecanbeonlyaccessedinthisfunction.• Variableswillbelocalizedwhenweapplyablock(brace{})whentheyaredeclared.(scope)
Declarationofavariable
�15Lecture218April2019
• giveanametoaconstant;• theconstantvariablewillnotchangethevalueduringrunning-time.
• Useofpreprocessordefinitiontonameavalue.• #definelineispreprocessordirective.• Note:NOSEMICOLONINPREPROCESSORDEFINITION.
Declarationofaconstant
�16Lecture218April2019
• Expressionsarestatementsfortypicalcalculations.• Here“+”isanoperator,whichevaluatethevalueofvariable1andvariable2.• Withanoperator,thevalueofvariablescanbechanged.• C++arithmeticoperators:+(addition),-(subtraction),*(multiplication),/(division),%(modulooperator)• Orderofprecedencefollowsmathematicalrule(discusslater).3-2*5/11=?7-6./5=?11.2-2.5/3.=?
Basicoperators
�17Lecture218April2019
• operatorssuchas:+=,-=,*=,/=,%=a+=bisthesametoa=a+b;• incrementanddecrementoperator:✓i++;++i;i--;--i;✓pre-incrementandpost-increment;✓pre-decrementandpost-decrement;
• Findthedifferencefollowingexpressions:
Basicoperators
�18Lecture218April2019
• Twoexpressioncomparedusingrelationalandcomparisonoperators.• Resultiseithertrueorfalse.• ==(equalto),>=(largerthanorequalto),<=(lessthanorequalto),>(largerthan),<(lessthan),!=(notequalto)• a=bb,setvaluebtoa,assignment• a==btrueifaequaltob,equality• Question:Isa=bequivalenttob=a?• Isa==bequivalenttob==a?
Basicoperators(relationalandcomparison)
�19Lecture218April2019
• booloperators:!,&&,||• !istheoperatorNOTforbooloperator.• &&and||operator:booloperatorANDandOR.
• conditionalternaryoperator(?)• condition?result1:result2• iftheconditionistrue,thevalueisresult1,otherwisethevalueisresult2.
Basicoperators
�20Lecture218April2019
• y=1+(x=5);• x=y=z=6;• (6+3)<=(1+2);• x/=y+6;• x=5;y=x++;cout<<y;• 7==5;• x=7+2%5;• 7==5+2?a,b
Basicoperators(exercise)
�21Lecture218April2019
Programanalysis-coding-executioncycle
�22Lecture218April2019
Programanalysis-coding-executioncycle
�23Lecture218April2019
Findtheperimeterandareaofarectangle.
perimeter=2*(length+width);area=length*width
Algorithm:1. Getthelengthoftherectangle;2. Getthewidthoftherectangle;3. Findtheperimeterbytheexpression;4. Findtheareausingtheequation.
Programanalysis-coding-executioncycle(example)
�24Lecture218April2019
Everysalespersonhasabasesalary.Thesalespersonalsoreceivesabonusat theendofeachmonth,basedon the following criteria: Ifthe salesperson has been with the store for five years or less, thebonus is $10 for each year that he or she hasworked there. If thesalesperson has been with the store for more than five years, thebonus is $20 for each year that he or she has worked there. Thesalespersoncanearnanaddiyonalbonusasfollows:Ifthetotalsalesmade bythesalespersonforthemonthareatleast$5,000butlessthan$10,000,heorshereceivesa3%commissiononthesale.Ifthetotal sales made by the salesperson for the month are at least$10,000,heorshereceivesa6%commissiononthesale.
Programanalysis-coding-executioncycle
�25Lecture218April2019
Definevariables:
BaseSalary:basesalary
noofServiceYears:numberofserviceyears
totalSales:totalsalesmadebythesalesperson
addiDonalBonus:addiyonalbonus
Algorithm:
if(noofServiceYearsislessthanorequaltofive)
bonus=10*noOfServiceYears
otherwise
bonus=20*noOfServiceYears
Programanalysis-coding-executioncycle
�26Lecture218April2019
Nextdeterminetheaddiyonalbonus:
if(totalSalesislessthan5000)
addiDonalBonus=0
otherwise
if(totalSalesisgreaterthanorequalto5000andtotalSalesislessthan10000)
addiDonalBonus=totalSales*0.03
otherwise
addiDonalBonus=totalSales*0.06
Finally,getthepaycheck.
Programanalysis-coding-executioncycle
�27Lecture218April2019
Algorithm:
1. getbaseSalary;
2. getnoOfServiceYears;
3. checkbonususingthefollowingformula:
if(noofServiceYearsislessthanorequaltofive)
bonus=10*noOfServiceYears
otherwise
bonus=20*noOfServiceYears
4.gettotalSales;
5.CalculateaddiDonalBonususingfollowingformula:
Programanalysis-coding-executioncycle
�28Lecture218April2019
if(totalSalesislessthan5000)
addiDonalBonus=0
otherwise
if(totalSalesisgreaterthanorequalto5000andtotalSalesislessthan10000)
addiDonalBonus=totalSales*0.03
otherwise
addiDonalBonus=totalSales*0.06
6.CalculatepayCheckusingequayon:
payCheck=baseSalary+bonus+addiDonalBonus
• Todisplaythetexttoscreen,wesendittoobjectcoutusinginsertionoperator<<.• Togetinputbykeyboard,wesendittoobjectcinusingextractionoperator>>.
• Trytowriteasimpleaddoperationonyourcomputer.
Displaytheresultwithstreams
• Statementsandcontrolflow(if,while,for,case…)• functions.
Nextlecture
�30Lecture218April2019