Download - Lecture 19 Part 1.pdf
-
7/27/2019 Lecture 19 Part 1.pdf
1/16
1992-2012 by Pearson Education, Inc. & John Wiley & SonsSome portions are adopted from C++ f or Everyone by Horstmann
ENGR 1200U Introduction to Programming
Lecture 19
Modular Programming with Functions (Chapter 6)
(contd)
Dr. Eyhab Al-Masri
ENGR 1200U
Winter 2013 - UOIT
A program may be broken downinto a set of manageablefunctions, or modules.
Thisiscalled________________________________.
ModularProgramming
-
7/27/2019 Lecture 19 Part 1.pdf
2/16
ENGR 1200U
Winter 2013 - UOIT
What is a function call?What is a function definition?
Afunctioncallisastatementthatcausesafunctionto
execute.
Afunctiondefinitioncontainsthestatementsthatmakeup
the
functions.
ENGR 1200U
Winter 2013 - UOIT
When creating a function, you mustcreate its __________ . It consists of
the following parts:
definition:Allfunctiondefinitionshavethefollowingparts:
Name Everyfunctionmusthaveaname
Parameterlist Listofvariablesthatholdthevalues
beingpassedtothefunction.
Body Bodyofthefunction(setofstatements
thatcarryoutthetaskofthefunction
isperforming).Enclosedinbraces.
-
7/27/2019 Lecture 19 Part 1.pdf
3/16
ENGR 1200U
Winter 2013 - UOIT
Fill-in the blanks:
double cube_volume(double side_length)
{
double volume=side_length *side_length *side_length;
return volume;
}
return type name parameter list
body
ENGR 1200U
Winter 2013 - UOIT
What is the output of the following program?
Hellofrommain.
HellofromthefunctiondisplayMessage.
Backinfunctionmainagain.
-
7/27/2019 Lecture 19 Part 1.pdf
4/16
ENGR 1200U
Winter 2013 - UOIT
What is a function prototype?
Afunctionprototypeeliminatestheneedtoplacea
functiondefinitionbeforeallcallstothefunction.
ENGR 1200U
Winter 2013 - UOIT
When a function is called, theprogram may send values into thefunction. Values that are sent in afunction call are called _________.
arguments
Example:result=pow(2.0,4.0);
A
parameter is
a
special
variable
that
holds
a
value
beingpassedasanargumentintoafunction.
Example:voiddisplayValue(int num)
-
7/27/2019 Lecture 19 Part 1.pdf
5/16
ENGR 1200U
Winter 2013 - UOIT
What is the output of the following program?
Givenaninputof
487
Outputis:
Thesumis19
1//Thisprogramdemonstratesafunctionwiththreeparameters.
2
#include 3using namespace std;4
5//Functionprototype
6void showSum(int num1,int num2,int num3);
7
8int main()
9{
10int value1,value2,value3;
11
12//Get3integers
13coutvalue2>>value3;
16
17//CallshowSum,passing3arguments
18showSum(value1,value2,value3);
19return 0;
20
}21
22void showSum(int num1,int num2,int num3)
23{23 cout
-
7/27/2019 Lecture 19 Part 1.pdf
6/16
ENGR 1200U
Winter 2013 - UOIT
What is the output of the following program?
ProgramOutput
Inmainnumberis12
InchangeMe,thevaluehasbeenchangedto0Backinmainagain,numberisstill12
#include
using namespace std;
void changeMe(int aValue);
int main()
{
int number=12;
cout
-
7/27/2019 Lecture 19 Part 1.pdf
7/16
ENGR 1200U
Winter 2013 - UOIT
Can a function send a value back toa part of a program? (contd)
int sum(int num1,int num2)
{
return num1+num2;
}
//assumevalues20and4
0arepassedintosum
ENGR 1200U
Winter 2013 - UOIT
Can functions return true or falsevalues?
Yes. Sometimes there is a
need for a function that
tests an argument and
returns a true or falsevalue indicating whether or
not a condition is
satisfied.
bool isValid(int number)
{
bool status;
if (number>=1&&number
-
7/27/2019 Lecture 19 Part 1.pdf
8/16
ENGR 1200U
Winter 2013 - UOIT
Can functions return true or falsevalues? (contd)
This code snippet shows an if/else statement that makes a
call to the function:
int value=20;
if (isValid(value))
cout
-
7/27/2019 Lecture 19 Part 1.pdf
9/16
ENGR 1200U
Winter 2013 - UOIT
When the function begins, its parameter variables andany local variables it defines are created in memory
When function ends, these variables are destroyed
This means that any values stored in a functions
parameters or local variables are lost between calls tothe function.
A local variable exists only while the function it isdefined in is executing
This is known as lifetime of a local variable
ENGR 1200U
Winter 2013 - UOIT
int sum(int num1,int num2)
{
int result=num1+num2;
return result;}
It is possible to use parameter variablesto initialize local variables
-
7/27/2019 Lecture 19 Part 1.pdf
10/161
ENGR 1200U
Winter 2013 - UOIT
Global constants are typically used to representunchanging values that are needed throughout aprogram
Example: Suppose a banking program uses anamed constant to represent an interest rate. If interest rate is used in several functions, it is easier to
create a global constant, rather than a local namedconstant in each function
A global constant is a named constant that isavailable to every function in a program
ENGR 1200U
Winter 2013 - UOIT
You cannot have two local variables with thesame name in the same function
This applies to parameter variables as well
A parameter variable, in essence, a local variable.Hence, you cannot give a parameter variable and a localvariable in the same function the same name!
However, you can have a parameter or localvariable with the same name as a global variableor constant
-
7/27/2019 Lecture 19 Part 1.pdf
11/161
ENGR 1200U
Winter 2013 - UOIT
This is because local variables are destroyedwhen a function terminates
Local variables are also recreated when the
function starts again
If a function is called more than once in aprogram, the values stored in the functions localvariables do not persist between function calls
ENGR 1200U
Winter 2013 - UOIT
This is accomplished by making the variable static Static variables are not destroyed when a function
returns They exist for the entire lifetime of the program, even
though their scope is only the function in which they aredefined
Sometimes it is desirable for a program toremember what value is stored in a localvariable between function calls.
-
7/27/2019 Lecture 19 Part 1.pdf
12/161
ENGR 1200U
Winter 2013 - UOIT
What is a reference variable?
Areferencevariableisavariablethatreferencesthe
memorylocationofanothervariable
Anychangemadetothereferencevariableisactually
made
to
the
one
it
references
ENGR 1200U
Winter 2013 - UOIT
What is the output of the following program?
ProgramOutput
Inmain,valueis4
NowcallingdoubleNum...
Nowbackinmain,valueis8
//Thisprogramusesareferencevariableasafunctionparameter.
#include
using namespace std;
void doubleNum(int &refVar);
int main()
{
int value=4;cout
-
7/27/2019 Lecture 19 Part 1.pdf
13/161
ENGR 1200U
Winter 2013 - UOIT
New programmers often have difficulty determiningwhen an argument should be passed to a function byreference and when it should be passed by value
Here are some general guidelines: When an argument is a constant, it must be passed by
value
When a variable is passed as an argument should nothave its value changed, it should be passed by value
This protects it from being altered
ENGR 1200U
Winter 2013 - UOIT
Here are some general guidelines (contd):
When two or more variables passed as arguments to afunction need to have their values changed by thatfunction, they should be passed by reference
When a copy of an argument cannot reasonably orcorrectly be made, such as when the argument is a file
stream object, it must be passed by reference
-
7/27/2019 Lecture 19 Part 1.pdf
14/161
ENGR 1200U
Winter 2013 - UOIT
Here are three common instances when referenceparameters are used:
When data values being input in a function need to beknown by the calling function
When a function must change existing values in thecalling function
When a file stream object is passed to a function
ENGR 1200U
Winter 2013 - UOIT
Sometimes you will create two or more functions that perform thesame operation, but use a different set of parameters, orparameters of different data types
Example: Suppose there is a square function that uses a double
parameter
Also, suppose you also wanted a square function that worksexclusively with integers and accepts an int as its argument
Both functions would do the same thing, return the square of theirargument
The only difference is the data type involved in the operation
A Two or more functions may have the same name, aslong as their parameter lists are different
-
7/27/2019 Lecture 19 Part 1.pdf
15/161
ENGR 1200U
Winter 2013 - UOIT
Example: squareInt, and squareDouble
C++, however, allows you to overload function names
This means you may assign the same name to multiplefunctions, as long as their parameters lists aredifferent
If you were to use both these functions in the same program, youcould assign a unique name to each function
ENGR 1200U
Winter 2013 - UOIT
#include
#include
using namespace std;
int square(int);
double square(double);
int main()
{
int userInt;
double userReal;
cout
userInt >>
userReal;cout
-
7/27/2019 Lecture 19 Part 1.pdf
16/16
ENGR 1200U
Winter 2013 - UOIT
The exit() function causes a program to terminate, regardless ofwhich function or control mechanism is executing
#include
#include //Neededtousetheexitfunctioninsomecompilers
using namespace std;
void someFunction();
int main()
{
someFunction();
return 0;
}
void someFunction()
{
cout