You are on page 1of 16

ENGR 1200U Introduction to Programming Lecture 19 Modular Programming with Functions (Chapter 6) (contd)

Dr. Eyhab Al-Masri

1992-2012 by Pearson Education, Inc. & John Wiley & Sons Some portions are adopted from C++ for Everyone by Horstmann

A program may be broken down into a set of manageable functions, or modules.

Thisiscalled________________________________. ModularProgramming

ENGR 1200U Winter 2013 - UOIT

What is a function call? What is a function definition?

Afunctioncallisastatementthatcausesafunctionto execute. Afunctiondefinitioncontainsthestatementsthatmakeup thefunctions.

ENGR 1200U Winter 2013 - UOIT

When creating a function, you must create its __________ . It consists of the following parts:
definition: Allfunctiondefinitions havethefollowing parts: Name Parameterlist Everyfunctionmusthaveaname Listofvariablesthatholdthevalues beingpassedtothefunction. Bodyofthefunction(setofstatements thatcarryoutthetaskofthefunction isperforming).Enclosedinbraces.

Body
ENGR 1200U Winter 2013 - UOIT

Fill-in the blanks:

return type

name

parameter list

double cube_volume(double side_length) { double volume=side_length *side_length *side_length; return volume; } body
ENGR 1200U Winter 2013 - UOIT

What is the output of the following program?

Hellofrommain. HellofromthefunctiondisplayMessage. Backinfunctionmainagain.


ENGR 1200U Winter 2013 - UOIT

What is a function prototype?

Afunctionprototypeeliminatestheneedtoplacea functiondefinitionbeforeallcallstothefunction.

ENGR 1200U Winter 2013 - UOIT

When a function is called, the program may send values into the function. Values that are sent in a function call are called _________.

arguments Example:result=pow(2.0,4.0); Aparameter isaspecialvariablethatholdsavalue beingpassedasanargumentintoafunction. Example:voiddisplayValue(int num)

ENGR 1200U Winter 2013 - UOIT

What is the output of the following program?


1//Thisprogramdemonstratesafunctionwiththreeparameters. 2#include <iostream> 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 13cout<<"EnterthreeintegersandIwilldisplay"; 14cout<<"theirsum:"; 15cin>>value1>>value2>>value3; 16 17//CallshowSum,passing3arguments 18showSum(value1,value2,value3); 19return 0; 20} 21 22void showSum(int num1,int num2,int num3) 23{ 23cout<<"Thesumis" <<(num1+num2+num3)<<endl; 25}

Givenaninputof 487 Outputis: Thesumis19

ENGR 1200U Winter 2013 - UOIT

What does it mean by the term pass by value?

Whenanargumentispassedintoaparameterbyvalue, onlyacopyoftheargumentsvalueispassed. Changestotheparameterdonotaffecttheoriginal argument. Thatis,ifaparametersvalueischangedinsidea function,ithasnoeffectontheoriginalargument.

ENGR 1200U Winter 2013 - UOIT

What is the output of the following program?


#include <iostream> using namespace std; void changeMe(int aValue); int main() { int number=12; cout<<"Inmainnumberis" <<number<<endl; changeMe(number); cout<<"Backinmainagain,numberisstill" <<number<<endl; return 0; } void changeMe(int myValue) { myValue=0; cout<<"InchangeMe,thevaluehasbeenchangedto" <<myValue<<endl; } ProgramOutput Inmainnumberis12 InchangeMe,thevaluehasbeenchangedto0 Backinmainagain,numberisstill12

ENGR 1200U Winter 2013 - UOIT

Can a function send a value back to a part of a program?

Yes.Datamaybepassedintoafunctionbywayof parametervariables.Datamayalsobereturnedfroma functionbacktothestatementthatcalledit. Functionsthatreturnavalueareknownasvalue returningfunctions.

ENGR 1200U Winter 2013 - UOIT

Can a function send a value back to a 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 false values?

Example

Yes. Sometimes there is a need for a function that tests an argument and returns a true or false value indicating whether or not a condition is satisfied.

bool isValid(int number) { bool status; if (number>=1&&number<=100) status=true; else status=false; return status; }

ENGR 1200U Winter 2013 - UOIT

Can functions return true or false values? (contd)

This code snippet shows an if/else statement that makes a call to the function:
Calling the isValid function:
int value=20; if (isValid(value)) cout<<"Thevalueiswithinrange.\n"; else cout<<"Thevalueisoutofrange.\n";

ENGR 1200U Winter 2013 - UOIT

What is the difference between local and global variables?

Alocalvariableisdefinedinsideafunctionandisnot accessibleoutsidethefunction. Aglobalvariableisdefinedoutsideallfunctionsandis accessibletoallfunctionsinitsscope.

ENGR 1200U Winter 2013 - UOIT

A local variable exists only while the function it is defined in is executing This is known as lifetime of a local variable

When the function begins, its parameter variables and any 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 to the function.

ENGR 1200U Winter 2013 - UOIT

It is possible to use parameter variables to initialize local variables


int sum(int num1,int num2) { int result=num1+num2; return result; }

ENGR 1200U Winter 2013 - UOIT

A global constant is a named constant that is available to every function in a program

Global constants are typically used to represent unchanging values that are needed throughout a program Example: Suppose a banking program uses a named 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 named constant in each function

ENGR 1200U Winter 2013 - UOIT

You cannot have two local variables with the same 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 local variable in the same function the same name!

However, you can have a parameter or local variable with the same name as a global variable or constant

ENGR 1200U Winter 2013 - UOIT

10

If a function is called more than once in a program, the values stored in the functions local variables do not persist between function calls

This is because local variables are destroyed when a function terminates Local variables are also recreated when the function starts again

ENGR 1200U Winter 2013 - UOIT

Sometimes it is desirable for a program to remember what value is stored in a local variable between function calls.

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 are defined

ENGR 1200U Winter 2013 - UOIT

11

What is a reference variable?

Areferencevariableisavariablethatreferencesthe memorylocationofanothervariable Anychangemadetothereferencevariableisactually madetotheoneitreferences

ENGR 1200U Winter 2013 - UOIT

What is the output of the following program?


//Thisprogramusesareferencevariableasafunctionparameter. #include <iostream> using namespace std; void doubleNum(int &refVar); int main() { int value=4; cout<<"Inmain,valueis" <<value<<endl; cout<<"NowcallingdoubleNum..." <<endl; doubleNum(value); cout<<"Nowbackinmain,valueis" <<value<<endl; return 0; } void doubleNum(int &refVar) { refVar*=2; } ProgramOutput Inmain,valueis4 NowcallingdoubleNum... Nowbackinmain,valueis8

ENGR 1200U Winter 2013 - UOIT

12

New programmers often have difficulty determining when an argument should be passed to a function by reference 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 not have 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 a function need to have their values changed by that function, they should be passed by reference When a copy of an argument cannot reasonably or correctly be made, such as when the argument is a file stream object, it must be passed by reference

ENGR 1200U Winter 2013 - UOIT

13

Here are three common instances when reference parameters are used:
When data values being input in a function need to be known by the calling function When a function must change existing values in the calling function When a file stream object is passed to a function

ENGR 1200U Winter 2013 - UOIT

A Two or more functions may have the same name, as long as their parameter lists are different

Sometimes you will create two or more functions that perform the same operation, but use a different set of parameters, or parameters 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 works exclusively with integers and accepts an int as its argument
Both functions would do the same thing, return the square of their argument The only difference is the data type involved in the operation

ENGR 1200U Winter 2013 - UOIT

14

If you were to use both these functions in the same program, you could assign a unique name to each function

Example: squareInt, and squareDouble C++, however, allows you to overload function names This means you may assign the same name to multiple functions, as long as their parameters lists are different

ENGR 1200U Winter 2013 - UOIT

#include <iostream> #include <iomanip> using namespace std; int square(int); double square(double);

int square(int number) { return number*number; } double square(double number) { return number*number; }

int main() { int userInt; double userReal; cout <<"Enteranintegerandafloatingpointvalue:"; cin >>userInt >>userReal; cout <<"Herearetheirsquares:"; cout <<fixed<<showpoint <<setprecision(2); cout <<square(userInt)<<"and" <<square(userReal)<<endl; return 0; }
ENGR 1200U Winter 2013 - UOIT

15

The exit() function causes a program to terminate, regardless of which function or control mechanism is executing
#include <iostream> #include <cstdlib> using namespace std; void someFunction(); int main() { someFunction(); return 0; } //Neededtousetheexitfunctioninsomecompilers

void someFunction() { cout <<"Thisprogramterminateswiththeexitfunction.\n"; cout <<"Bye!\n"; exit(0); cout <<"Thismessagewillneverbedisplayed\n"; cout <<"becausetheprogramhasalreadyterminated.\n"; }

Program Output This program terminates with the exit function. Bye!

ENGR 1200U Winter 2013 - UOIT

It is common to invoke a function repeatedly with the same argument value for a particular parameter. In such cases, you can specify parameters with a default argument
#include <iostream> VoidboxVolume(int length=1,int width=1,int height=1); using namespace std; void someFunction(); int boxVolume(int length,int width,int height) { returnlength*width*height; }

Program Output This program terminates with the exit function. Bye!

int main() { int volume=boxVolume (1,2); return 0; }

ENGR 1200U Winter 2013 - UOIT

16

You might also like