C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together...
Transcript of C++ programing for beginners€¦ · • Functions can be - like miniature programs; - put together...
Lecture4
C++programingforbeginners
1May2019
Lecturer:Dr.AnleWang&Dr.SergeySukhomlinov
�1
E-mail:[email protected]
Lecture4
• Learnaboutstandardfunctionsanddiscoverhowtousetheminaprogram;abs(x)• Learnaboutuser-definedfunctions;• Examinevalue-returningfunctions;• Explorehowtoconstructanduseauser-definedfunctioninaprogram;
• Afterthislecture,youshouldbeableto:✓Constructanduseauser-definedfunction;
1May2019 �2
ContentsofLecture4
• Functionsarelikebuildingblocks;• Advantagesofusingfunctions:- Allowcomplicatedprogramstodividedintomanageablepieces;- Focusonthispartofprogramandconstructit,debugitandmakeitperfect;- Differentprogrammercanworkondifferentfunctionsinparallel;- Canbere-used;- Enhanceprogramreadability.
Whatisafunction?
�3Lecture41May2019
• Functionscanbe- likeminiatureprograms;- puttogethertoformalargeprogram.
• Functioncanbecategorized:- predefinedfunctions;sqrt(x),abs(x)…- user-definedfunctions.
Whatisafunction?
�4Lecture41May2019
• Mathfunctionsincmathheader;suchassqrt()• Predefinedfunctionsarecategorizedbyseparatelibraries;• sqrt(),abs(),floor(),ceil(),min(),max()…
Predefinedfunctions
�5Lecture41May2019
• User-definedfunctionsarenamedsectionsofcodecanbecalledfromanywhereintheprogram;•
User-definedfunctions
�6Lecture41May2019
• Theruletonamethefunctionisthesameasnamingvariables.• Trytoavoidtogivethesamenameofpredefinedfunctions.
User-definedfunctions
�7Lecture41May2019
• Parameterspassedbyvalue;• Thereturntypenameofafunctionisthetypethatthefunctionevaluatestowhencalled;• Theargumentcanbechangedwithinthefunctionwithoutchangingthevaluesoutsidethefunction;
User-definedfunctions
�8Lecture41May2019
• Functionparametersarevariableswithatypeandaname,separatedwithacomma;formalparameter• Theargumentsareinscopeofthefunctionbody;• Withoutparameters,requireparentheses:funtion();
User-definedfunctions
�9Lecture41May2019
• Functionbodycancontainanycode,justlikemainfunction;• Functionalsocancallotherfunction,includingthemselves(recursion).
User-definedfunctions
�10Lecture41May2019
• Specifiedthevalueofthefunctionevaluatesto;• Exitthefunctionandreturnthecodethatcalledit;• Canoccuranywhereinthefunctionbody(if);• voidfunctionneedsnoreturnstatement.
User-definedfunctions
�11Lecture41May2019
• Thereturnvalue0ofmainfunctionmeansthefunctionexitsnormallyandendssuccessfully.- return0:theprogramwassuccessful;- returnEXIT_SUCCESS:theprogramwassuccessful;(cstdlib.h)- returnEXIT_FAILURE:theprogramfailed.(cstdlib.h)
Returnvalueofmainfunction
�12Lecture41May2019
• Functionsmustbedeclaredbeforetheyarecalled;- thewholefunctioncanbeputabovetheplaceitisplaced;- orthedeclarationcanbeputabovetheplaceitisplaced,andthefunctiondefinitionbelow.
User-definedfunctions
�13Lecture41May2019
• Theprogramstartsexecutionfrommainfunction;• Thenwhenthefunctioniscalled,executethefunction;• Afterthefinalstatementofthefunctionisexecuted,jumpbackimmediatelytothepointfollowingthefunctioncalled.
Executionflow
�14Lecture41May2019
!
"
#
$
• voidfunctiondoesnotreturnanyvalue.• Formalparameterisoptional(alsoinvalue-returnfunction);• Callvoidfunctionwith();
Voidfunction
�15Lecture41May2019
• Globalvariables:identifiersdeclaredoutsideofeachfunctiondefinition• Localvariables:identifiersdeclaredwithinafunction.•
Localandglobalvariables
�16Lecture41May2019
• Whenmorethanonefunctionusetheglobalvariables,sometimessomethinggoeswrong:- Hardtofindthereasonandtheplacewentwrong;- Problemcausedbythisareamaycauseerrorinthatarea;
• TRYTOUSEGLOBALVARIABLECAREFULLY!• Localvariablesonlycanbeappliedinthescopeofthisfunction.
Localandglobalvariables
�17Lecture41May2019
• Severalfunctionscanhavethesamename;• Twofunctionshavedifferentformalparameterlists;- Differentnumberofparameters;- Samenumberofparameterswithdifferentdatatype;
• Functionoverloading:createseveralfunctionswithsamename.
• Writeasmallprogramtocomparetwoorthreenumbersandfindtheminimumonewithfunctionoverloading;
Functionoverloading
�18Lecture41May2019
• Functioncanbecalledbythemselves,usefulforsortingelements,recursivefunctions…• Avoidinfiniteloopwithsomebasiccontrolstructures.
Recursivenessoffunction
�19Lecture41May2019
Recursivenessoffunction
�20Lecture41May2019
forloop
forloopwithcallingfunctionrecursivefunction
• valueparameter:aformalparameterthatreceivesacopyofthecontentofcorrespondingactualparameter;• referenceparameter:aformalparameterthatreceivethelocation(memoryaddress)ofthecorrespondingactualparameter.•
Valuevariables,referencevariables
�21Lecture41May2019
• Intheexample,wewilltrytowriteaprogramtodeterminethemaximumandminimumnumberofanintegernumberarray.14172536549012• Thestructureofmainfunction:- initializethevariables,setthenumberofintegers,initialmaximumandminimumvalues;- Readanumberfromkeyboard;- Comparethenumberwithinitialmaximumandminimumvalue,ifconditionfulfills,replacetheinitialvaluewiththisnumber;- repeatstep2and3withreadingthenumberlist;- Displaytheresultofmaximumandminimumvalue.
Programingexample
�22Lecture41May2019
• Foreachstep,definethefunction:- initializethevariables,setthenumberofintegers,initialmaximumandminimumvalues;initParams()- Readanumberfromkeyboard;inputNum()- Comparethenumberwithinitialmaximumandminimumvalue,ifconditionfulfills,replacetheinitialvaluewiththisnumber;maximum(),minimum()- repeatstep2and3withreadingthenumberlist;loopstructure- Displaytheresultofmaximumandminimumvalue.dispResult()
Programingexample
�23Lecture41May2019
• Themainfunctioncanbe:
Programingexample
�24Lecture41May2019
• 1.Initializethevariables,setthenumberofintegers,initialmaximumandminimumvalues;initParams()• Trytofigureoutwhichisglobalvariableandlocalvariable.•
Programingexample
�25Lecture41May2019
• 2.Readanumberfromkeyboard;inputNum()
• 3.Comparethenumberwithinitialmaximumandminimumvalue,ifconditionfulfills,replacetheinitialvaluewiththisnumber;minimum(),maximum()•
Programingexample
�26Lecture41May2019
• 4.Displaytheresultofmaximumandminimumvalue.dispResult()
Programingexample
�27Lecture41May2019
Programingexample
�28Lecture41May2019
• Writeaprogramcontainstwofunctionsminimum()andmaximum()tocomparetwointegernumbers;• Writeafunctiontodetermineiftheinputnumberisaprimenumber,thenumbercanbeinputinmainfunction.• Writeafunctiontogetthevalueofa!+b!+c!,inputandoutputthevaluebymainfunction.
Exercises
�29Lecture41May2019
Lecture4
• Firstandsecond-orderalgorithm;• Precisionanderror;
1May2019 �30
NextLecture