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

C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

Lecture4

C++programingforbeginners

1May2019

Lecturer:Dr.AnleWang&Dr.SergeySukhomlinov

�1

E-mail:[email protected]

Page 2: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

Lecture4

• Learnaboutstandardfunctionsanddiscoverhowtousetheminaprogram;abs(x)• Learnaboutuser-definedfunctions;• Examinevalue-returningfunctions;• Explorehowtoconstructanduseauser-definedfunctioninaprogram;

• Afterthislecture,youshouldbeableto:✓Constructanduseauser-definedfunction;

1May2019 �2

ContentsofLecture4

Page 3: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Functionsarelikebuildingblocks;• Advantagesofusingfunctions:- Allowcomplicatedprogramstodividedintomanageablepieces;- Focusonthispartofprogramandconstructit,debugitandmakeitperfect;- Differentprogrammercanworkondifferentfunctionsinparallel;- Canbere-used;- Enhanceprogramreadability.

Whatisafunction?

�3Lecture41May2019

Page 4: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Functionscanbe- likeminiatureprograms;- puttogethertoformalargeprogram.

• Functioncanbecategorized:- predefinedfunctions;sqrt(x),abs(x)…- user-definedfunctions.

Whatisafunction?

�4Lecture41May2019

Page 5: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Mathfunctionsincmathheader;suchassqrt()• Predefinedfunctionsarecategorizedbyseparatelibraries;• sqrt(),abs(),floor(),ceil(),min(),max()…

Predefinedfunctions

�5Lecture41May2019

Page 6: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• User-definedfunctionsarenamedsectionsofcodecanbecalledfromanywhereintheprogram;•

User-definedfunctions

�6Lecture41May2019

Page 7: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Theruletonamethefunctionisthesameasnamingvariables.• Trytoavoidtogivethesamenameofpredefinedfunctions.

User-definedfunctions

�7Lecture41May2019

Page 8: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Parameterspassedbyvalue;• Thereturntypenameofafunctionisthetypethatthefunctionevaluatestowhencalled;• Theargumentcanbechangedwithinthefunctionwithoutchangingthevaluesoutsidethefunction;

User-definedfunctions

�8Lecture41May2019

Page 9: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Functionparametersarevariableswithatypeandaname,separatedwithacomma;formalparameter• Theargumentsareinscopeofthefunctionbody;• Withoutparameters,requireparentheses:funtion();

User-definedfunctions

�9Lecture41May2019

Page 10: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Functionbodycancontainanycode,justlikemainfunction;• Functionalsocancallotherfunction,includingthemselves(recursion).

User-definedfunctions

�10Lecture41May2019

Page 11: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Specifiedthevalueofthefunctionevaluatesto;• Exitthefunctionandreturnthecodethatcalledit;• Canoccuranywhereinthefunctionbody(if);• voidfunctionneedsnoreturnstatement.

User-definedfunctions

�11Lecture41May2019

Page 12: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Thereturnvalue0ofmainfunctionmeansthefunctionexitsnormallyandendssuccessfully.- return0:theprogramwassuccessful;- returnEXIT_SUCCESS:theprogramwassuccessful;(cstdlib.h)- returnEXIT_FAILURE:theprogramfailed.(cstdlib.h)

Returnvalueofmainfunction

�12Lecture41May2019

Page 13: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Functionsmustbedeclaredbeforetheyarecalled;- thewholefunctioncanbeputabovetheplaceitisplaced;- orthedeclarationcanbeputabovetheplaceitisplaced,andthefunctiondefinitionbelow.

User-definedfunctions

�13Lecture41May2019

Page 14: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Theprogramstartsexecutionfrommainfunction;• Thenwhenthefunctioniscalled,executethefunction;• Afterthefinalstatementofthefunctionisexecuted,jumpbackimmediatelytothepointfollowingthefunctioncalled.

Executionflow

�14Lecture41May2019

!

"

#

$

Page 15: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• voidfunctiondoesnotreturnanyvalue.• Formalparameterisoptional(alsoinvalue-returnfunction);• Callvoidfunctionwith();

Voidfunction

�15Lecture41May2019

Page 16: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Globalvariables:identifiersdeclaredoutsideofeachfunctiondefinition• Localvariables:identifiersdeclaredwithinafunction.•

Localandglobalvariables

�16Lecture41May2019

Page 17: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Whenmorethanonefunctionusetheglobalvariables,sometimessomethinggoeswrong:- Hardtofindthereasonandtheplacewentwrong;- Problemcausedbythisareamaycauseerrorinthatarea;

• TRYTOUSEGLOBALVARIABLECAREFULLY!• Localvariablesonlycanbeappliedinthescopeofthisfunction.

Localandglobalvariables

�17Lecture41May2019

Page 18: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Severalfunctionscanhavethesamename;• Twofunctionshavedifferentformalparameterlists;- Differentnumberofparameters;- Samenumberofparameterswithdifferentdatatype;

• Functionoverloading:createseveralfunctionswithsamename.

• Writeasmallprogramtocomparetwoorthreenumbersandfindtheminimumonewithfunctionoverloading;

Functionoverloading

�18Lecture41May2019

Page 19: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Functioncanbecalledbythemselves,usefulforsortingelements,recursivefunctions…• Avoidinfiniteloopwithsomebasiccontrolstructures.

Recursivenessoffunction

�19Lecture41May2019

Page 20: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

Recursivenessoffunction

�20Lecture41May2019

forloop

forloopwithcallingfunctionrecursivefunction

Page 21: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• valueparameter:aformalparameterthatreceivesacopyofthecontentofcorrespondingactualparameter;• referenceparameter:aformalparameterthatreceivethelocation(memoryaddress)ofthecorrespondingactualparameter.•

Valuevariables,referencevariables

�21Lecture41May2019

Page 22: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Intheexample,wewilltrytowriteaprogramtodeterminethemaximumandminimumnumberofanintegernumberarray.14172536549012• Thestructureofmainfunction:- initializethevariables,setthenumberofintegers,initialmaximumandminimumvalues;- Readanumberfromkeyboard;- Comparethenumberwithinitialmaximumandminimumvalue,ifconditionfulfills,replacetheinitialvaluewiththisnumber;- repeatstep2and3withreadingthenumberlist;- Displaytheresultofmaximumandminimumvalue.

Programingexample

�22Lecture41May2019

Page 23: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Foreachstep,definethefunction:- initializethevariables,setthenumberofintegers,initialmaximumandminimumvalues;initParams()- Readanumberfromkeyboard;inputNum()- Comparethenumberwithinitialmaximumandminimumvalue,ifconditionfulfills,replacetheinitialvaluewiththisnumber;maximum(),minimum()- repeatstep2and3withreadingthenumberlist;loopstructure- Displaytheresultofmaximumandminimumvalue.dispResult()

Programingexample

�23Lecture41May2019

Page 24: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Themainfunctioncanbe:

Programingexample

�24Lecture41May2019

Page 25: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• 1.Initializethevariables,setthenumberofintegers,initialmaximumandminimumvalues;initParams()• Trytofigureoutwhichisglobalvariableandlocalvariable.•

Programingexample

�25Lecture41May2019

Page 26: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• 2.Readanumberfromkeyboard;inputNum()

• 3.Comparethenumberwithinitialmaximumandminimumvalue,ifconditionfulfills,replacetheinitialvaluewiththisnumber;minimum(),maximum()•

Programingexample

�26Lecture41May2019

Page 27: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• 4.Displaytheresultofmaximumandminimumvalue.dispResult()

Programingexample

�27Lecture41May2019

Page 28: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

Programingexample

�28Lecture41May2019

Page 29: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

• Writeaprogramcontainstwofunctionsminimum()andmaximum()tocomparetwointegernumbers;• Writeafunctiontodetermineiftheinputnumberisaprimenumber,thenumbercanbeinputinmainfunction.• Writeafunctiontogetthevalueofa!+b!+c!,inputandoutputthevaluebymainfunction.

Exercises

�29Lecture41May2019

Page 30: C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together to form a large program. • Function can be categorized: - predefined functions;

Lecture4

• Firstandsecond-orderalgorithm;• Precisionanderror;

1May2019 �30

NextLecture