30
Lecture 2 C++ programing for beginners 19 April 2019 Lecturer: Dr. Anle Wang & Dr. Sergey Sukhomlinov 1 E-mail: [email protected]

C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Lecture2

C++programingforbeginners

19April2019

Lecturer:Dr.AnleWang&Dr.SergeySukhomlinov

�1

E-mail:[email protected]

Page 2: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Lecture2

• RememberthebasicstructureofaC++program(library,function,variables,statements,return)• NEVERmissapartofcurlybrace{},semicolon;attheendofstatement.• Useindentationandalsomakeitreadable.•

18April2019 �2

Somecommentsofcoding

Page 3: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Lecture2

• Explorebasicdatatypes,basicoperators,declarationofavariable;• Discoverhowtousearithmeticoperations;• Learnsimpleinputandoutputstream(cin,cout,cerr,clog).

• Afterthislecture,youshouldbeableto:✓BefamiliarwiththebasiccomponentsofaC++program;

✓Declarationofavariable,performsimplearithmeticoperationsandinputoroutputwhatyouwant,displayonscreen.

✓Becomefamiliarwiththeusagewithincrementanddecrementoperator.

18April2019 �3

ContentsofLecture2

Page 4: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Lecture219April2019 �4

AdetailedlookatC++codecomments

libraries

functions

• Asimpleprogrammustcontainsomebasiclibrariesandfunctions.Rememberthatmainfunctionisnecessary.

Page 5: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

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.

Page 6: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Lecture218April2019 �6

AdetailedlookatC++code

• Themainfunctioniscalledbytheoperatingsystemwhentheprogramstarts.

• AllC++programsmustdefineamainfunction.• Nowwewilllookintomoredetailsinthefunction,such

asvariables,operators,etc.

intmain(){declarevariablesstatementsreturn0;}

Page 7: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• Definevariableasaportionofmemorytostoreavalue.• C++isahigh-typedlanguage,everyvariableneedstohaveatype,definethekindofdatastored.✓C++definesnumbersofbasicdatatypes,suchasint,float,etc.✓TheC++libraryincludesmoretypes.✓Thetypeofavariablecannotbechangesatrun-time.

•Wemustdefineavariablebeforeusingit.

Whatisavariable?

Datatype variables setvaluetovariables

`

�7Lecture218April2019

Page 8: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• Consistofletters,digitsandtheunderscorecharacter(_);• Mustbeginwithaletterorunderscore;• Casesensitive:sum!=SUM• Illegalidentifiers:✓ helloworld(nospacebetweenletters)✓ helloworld!(noexclamation)✓ hello+world(nosymbol)✓ 1helloworld(identifiercannotbeginwithadigit)✓ double,if(keywordtoidentifydatatypes,operators)

Howtonameavariable?

�8Lecture218April2019

Page 9: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• Datatype:setofvaluestogetherwithasetofoperations.• C++datatypes:✓simple.✓structured.✓pointer.• SimpleC++datatypes:✓integral:numberswithdecimal.✓floating-point:decimalnumbers.✓enumeration:user-defineddatatype.✓char:singlecharacter,suchas‘$’.✓booleandatatype:trueorfalse.

Fundamentaldatatypes

�9Lecture218April2019

Page 10: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Fundamentaldatatypes

http://www.cplusplus.com/doc/tutorial/variables/�10Lecture218April2019

Page 11: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• char:Thesmallestintegraldatatype(1byte);• forcharacters:letters,digits,specialsymbols.• Insinglequotes:‘0’,‘#’,‘A’…• Whatis‘’?

• booltype:twovalues(true,false).• manipulateBooleanlogicaloperation.

Fundamentaldatatypes(char,bool)

�11Lecture218April2019

Page 12: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• integralnumberswithoutdecimal(4byte);• Neverusecommainanintegralnumber;• 12,-25697,• Positiveintegersdonotneedtohave+sign.• Findthedifferencebetweenfollowingexpression:2/3,2.0/3,2.0/3.0

Fundamentaldatatypes(int)

�12Lecture218April2019

Page 13: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• decimalnumber,scientificnotationinC++language;• floating-pointdatatype:✓float;(6-7digits)✓double;(12digits)✓longdouble;• maximumdigitsofadecimalnumber.• setprecisionforfloatingdatatype.setprecision

Fundamentaldatatypes(floating-point)

�13Lecture218April2019

Page 14: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• typeidentifier=initial_value;//c-likeinitialization• typeidentifier(initial_value);//structureinitialization• typeidentifier{initial_value}.//uniforminitialization

Declarationandinitializationofavariable

�14Lecture218April2019

Datatype variables setvaluetovariables

Page 15: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• Declareavariablebeforeuseit;• Whenavariableisdeclaredinonefunction,thevariablecanbeonlyaccessedinthisfunction.• Variableswillbelocalizedwhenweapplyablock(brace{})whentheyaredeclared.(scope)

Declarationofavariable

�15Lecture218April2019

Page 16: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• giveanametoaconstant;• theconstantvariablewillnotchangethevalueduringrunning-time.

• Useofpreprocessordefinitiontonameavalue.• #definelineispreprocessordirective.• Note:NOSEMICOLONINPREPROCESSORDEFINITION.

Declarationofaconstant

�16Lecture218April2019

Page 17: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• 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

Page 18: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• operatorssuchas:+=,-=,*=,/=,%=a+=bisthesametoa=a+b;• incrementanddecrementoperator:✓i++;++i;i--;--i;✓pre-incrementandpost-increment;✓pre-decrementandpost-decrement;

• Findthedifferencefollowingexpressions:

Basicoperators

�18Lecture218April2019

Page 19: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• 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

Page 20: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• booloperators:!,&&,||• !istheoperatorNOTforbooloperator.• &&and||operator:booloperatorANDandOR.

• conditionalternaryoperator(?)• condition?result1:result2• iftheconditionistrue,thevalueisresult1,otherwisethevalueisresult2.

Basicoperators

�20Lecture218April2019

Page 21: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• 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

Page 22: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Programanalysis-coding-executioncycle

�22Lecture218April2019

Page 23: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Programanalysis-coding-executioncycle

�23Lecture218April2019

Findtheperimeterandareaofarectangle.

perimeter=2*(length+width);area=length*width

Algorithm:1. Getthelengthoftherectangle;2. Getthewidthoftherectangle;3. Findtheperimeterbytheexpression;4. Findtheareausingtheequation.

Page 24: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

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.

Page 25: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Programanalysis-coding-executioncycle

�25Lecture218April2019

Definevariables:

BaseSalary:basesalary

noofServiceYears:numberofserviceyears

totalSales:totalsalesmadebythesalesperson

addiDonalBonus:addiyonalbonus

Algorithm:

if(noofServiceYearsislessthanorequaltofive)

bonus=10*noOfServiceYears

otherwise

bonus=20*noOfServiceYears

Page 26: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Programanalysis-coding-executioncycle

�26Lecture218April2019

Nextdeterminetheaddiyonalbonus:

if(totalSalesislessthan5000)

addiDonalBonus=0

otherwise

if(totalSalesisgreaterthanorequalto5000andtotalSalesislessthan10000)

addiDonalBonus=totalSales*0.03

otherwise

addiDonalBonus=totalSales*0.06

Finally,getthepaycheck.

Page 27: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

Programanalysis-coding-executioncycle

�27Lecture218April2019

Algorithm:

1. getbaseSalary;

2. getnoOfServiceYears;

3. checkbonususingthefollowingformula:

if(noofServiceYearsislessthanorequaltofive)

bonus=10*noOfServiceYears

otherwise

bonus=20*noOfServiceYears

4.gettotalSales;

5.CalculateaddiDonalBonususingfollowingformula:

Page 28: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

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

Page 29: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• Todisplaythetexttoscreen,wesendittoobjectcoutusinginsertionoperator<<.• Togetinputbykeyboard,wesendittoobjectcinusingextractionoperator>>.

• Trytowriteasimpleaddoperationonyourcomputer.

Displaytheresultwithstreams

Page 30: C++ programing for beginners · • Define variable as a portion of memory to store a value. • C++ is a high-typed language, every variable needs to have a type, define the kind

• Statementsandcontrolflow(if,while,for,case…)• functions.

Nextlecture

�30Lecture218April2019