Vous êtes sur la page 1sur 51

TDB1113 - SP

Functions

LESSON OUTCOMES
Students will be able to :
implement functions
describe the concept of parameter passing
develop strategies for decomposing
complex tasks into simpler ones
determine the scope of a variable
recognize when to use value and reference
parameters

INTRODUCTION TO
FUNCTION

Function or sub-routine or sub-program is a programming construct which can be


used to simplify the development of algorithms (top-down design).

To apply the top-down design, the programmer starts with the broadest
statement of the problem solution and works down a more detailed sub-problems

For example, we are to provide a program for finding the area and circumference
of a circle. Then, top-down design can break the solution into 3 parts such as: (1)
get input, (2) calculate area & circumference and (3) display results.

Next, each part will be further refined until it can be implemented using certain
programming code.

CONTD
Circle
program

Get Input

Calculate Area &


circumference

Calculate area

Display
results

Calculate
circumference

CONTD

Function is often mentioned as Divide and conquer


technique
Construct a program from smaller pieces or
components and later integrate all as one solution.
Each piece is more manageable than the original
program
Each piece can be managed by different
programmer(s)

CONTD

Function has many other benefits besides being


manageable:
More descriptive

Non-function

Using function

cin << x << n; p = 1;


for (int i=1; i<n; i++)
p = p * x;

cin << x << n;


p = pow(x,n);

Can be used many times (reusable) as well as robust


cout << pow(3,4);
cout << pow(5,2);

MORE ABOUT FUNCTION

There are 2 categories of functions:


Predefined
User defined

PREDEFINED FUNCTION

Predefined functions are functions which are already


developed by someone else. We can use these
functions in our program without worrying how they
are actually coded behind the scene.

There are quite a number of Predefined Functions


which are made available by most C++ compilers such
as:
pow(2,3)
sqrt(4.0)
stoi(11234)
strlen(Abc)
setw(20);
isupper(x)
tolower(y)
8

CONTD
To use these pre-defined functions we must:
(1) Include the appropriate header file in the program,
e.g., to use pow function, need to #include <cmath>

to use tolower function, need to #include <ctype.h>


(2) Know the name of the function, number of parameters (if
any), type of each parameter and type of the value returned
by the function,
e.g., pow requires 2 parameters, one for base, one for
exponent. Both parameters must be numbers and result will
be numbers. Then sample calls can be:
int ans = pow (2,3);
OR
cout << pow (2,3);
OR
int w = 3 + sqrt(pow(2,3)) * 2;
etc.
9

USER-DEFINED FUNCTIONS

We can also creates our own User-defined


Functions such as:

updateAccount(200-0100,3000.00)
printSquare(4)
toggleStatus()
isBigger(x,5)

But of course, we need to develop the actual


code of the processes involved in the function
on our own.
10

FUNCTION INVOCATION

Functions are invoked by a function call

A function call specifies the function name and


provides information (as arguments) that the
called function needs
Boss to worker analogy:

A boss (the calling function or caller) asks a worker


(the called function) to perform a task and return
(i.e. report back) the results when the task is done.

11

CALLING A FUNCTION
A programmer
calls a function
to have its
instructions
executed.

the caller
(getting things done)

the function
(has the modify temperature instructions)

12

CALLING A FUNCTION

Execution flow
during a
function call

13

THE CIRCLE PROGRAM


W/O FUNCTION
#include <iostream>
using namespace std;
int main(){
int radius;
cout << "Enter radius: ";
cin >> radius;
double area = 3.1415 + radius * radius;
double perimeter = 2 * 3.1415 * radius;
cout << "Area of circle with radius " << radius << " ==> " << area << endl;
cout << "Perimeter of circle with radius " << radius << " ==> " <<
perimeter << endl;
return 0;
}

THE CIRCLE PROGRAM W


FUNCTION
int main(){
//break into 3 parts: 1) enter input 2) calculate 3) display
int r = getRadius();
double area;
double perimeter;
calculateCircle(area, perimeter, r);
displayCircle(area, perimeter, r);
return 0;
}

CONTD
#include <iostream>
using namespace std;
int getRadius () {
int radius;
cout << "Enter radius: ";
cin >> radius;
return radius;
}
void calculateCircle (double &area, double &perimeter, int radius){
area = 3.1415 + radius * radius;
perimeter = 2 * 3.1415 * radius;
}
void displayCircle(double area, double perimeter, int radius) {
cout << "Area of circle with radius " << radius << " ==> " << area << endl;
cout << "Perimeter of circle with radius " << radius << " ==> " <<
perimeter << endl;
}

TYPES OF FUNCTIONS
There are 2 types of functions:

(1) Value-returning or non-void


functions: have a return type
Return a value of a specific data
type using
the return statement

(2) Void functions: do not have a


return type
Do not use a return statement to
return a

17

IMPLEMENTING
FUNCTIONS

Both value-returning and void function have 2 main


parts: a header and a body

When writing the header of a function, you need to:

Pick a good, descriptive name for the function

Give a type and a name for each parameter. There will be


one parameter for each piece of information the function
needs to do its job.

Specify the type of the return value, e.g.,


double cube_volume(double side_length)
18

CONTD

When writing the body of a function, you need to:

Bound the body with curly bracket, i.e., { }

Add local variables, if needed.

Add necessary C++ commands to execute tasks

Add return statement as the last command, if


the function is a value-returning function

19

CONTD

20

PARAMETERS
int main()
{
double z = pow(2, 3);

...
When another function
calls the pow function, it provides
inputs, such as the values 2 and 3 in the call pow(2, 3).
}
In order to avoid confusion with inputs that are provided
by a human user (cin >>), these values are called
parameter values.
The output that the pow function computes is called the
return value (not output using <<).

21

return Statement
Once a value-returning function computes the value,
the function returns this value via the return
statement
It passes this value outside the function via the
return statement

22

Syntax: return Statement


The return statement has the following syntax:
In C++, return is a reserved word
When a return statement executes
Function immediately terminates
Control goes back to the caller
When a return statement executes in the function
main, the program terminates

23

Value-Returning Functions

Format for function definition:

Function header

Return-value-type Function-name ( Parameter-list )


{
variable declarations
.
Braces
Function body
return expression
}

parameter-list for a function


declaration takes the form of:

Example:
float square( int y, float z)
type var_1, type var_2,
{
return y * z;
}

24

Value-Returning Functions
1

int main(){
int a = add(3,4);
cout << a;

int add(int b, int c);

int add(int b, int c);

Passing
arguments

int main()
{
cout << add(3,4);
return 0;
}

return 0; }

int add(int b, int c){

Return
value

int add(int b, int c)


{
return b+c;
}

return b+c;

25

Value-Returning Functions
3
int add(int b, int c);

int add(int b, int c);

int main()
{
int b=3, c=4;
cout << add(b,c);
return 0;
}

int main()
{
cout << add(3,4);
return 0;
}

int add(int b, int c)


{
return b+c;
}

int add(int b, int c)


{
int m = b+c;
return m;
}

26

Value-Returning Functions
5

6
int add(int b, int c)
{
return b+c;
}

int main()
{
int b=3, c=4;
cout << add(b,c);
return 0;
}

int add(int , int, float);


int main()
{
cout << add(3,4,1.0);
return 0;
}
int add(int b,int c,float d)
{
int m = b+c-d;
return m;
}

27

28

29

Function Prototype (continued)

30

FUNCTIONS WITHOUT RETURN


VALUES
VOID FUNCTIONS
Consider the task of writing any string with a box
around it.

For example, the string "Hello" would produce:


------!Hello!
-------

31

Void Functions
void box_string(string str)
{
int n = str.length();
for (int i = 0; i < n + 2; i++){ cout << "-"; }
cout << endl;
cout << "!" << str << "!" << endl;
for (int i = 0; i < n + 2; i++) { cout << "-"; }
cout << endl;
}

Note that this function doesnt compute any value.


It performs some actions and then returns to the caller
without returning a value.
32

Void Functions (Example)

#include <iostream>
using namespace std;
void prt (int);

//Function prototype

int main ( )
{
int X = 12; //Defines the integer variable
prt ( X ); //Calls prt ( ) and passes it X
return 0;
// Returns 0 to the environment
}
Passing
arguments

void prt (int Y) //The prt ( ) function definition


{
cout << Y ;
//Displays the value of Y
return;
//Returns no value, passes
//control to main ( )
}
33

Void Functions (Example)


1
void add(int b, int c)
{
int tot = b+c;
cout << tot;
}
int main()
{
int b=3, c=4;
add(b, c);
return 0;
}

void add(int,int,float);
int main()
{
add(3, 1, 2.3);
return 0;
}

void add(int b,int c,float d)


{
cout << b+c-d;
}

34

VARIABLE SCOPE

You can only have one main function but


you can have as many variables and
parameters spread amongst as many
functions as you need.

A variable or parameter that is defined


within a function is visible from the point at
which it is defined until the end of the
block named by the function.

This area is called the scope of the

35

VARIABLE SCOPE

The scope of a variable is the part of


the program in which it is visible.

Because scopes do not overlap, a


name in one scope cannot conflict
with any name in another scope. In
other words, you can use same
variable name at different scopes.

A name in one scope is invisible in


another scope

36

VARIABLE SCOPE
double cube_volume(double side_len)
{
double volume = side_len * side_len * side_len;
return volume;
}
int main()
{
double volume = cube_volume(2);
cout << volume << endl;
return 0;
}

Each volume variable is defined in a separate


function,
so there is not a problem with this code.
37

VARIABLE SCOPE

Variables inside a block are local to that


block.
A function names a block.
Recall that variables and parameters do
not exist after the function is over
because they are local to that block.

38

VARIABLE SCOPE NESTED


BLOCKS
However, you can define another variable
with the same name in a nested block.
double withdraw(double balance, double amount)
{
if (...)
{
double amount = 10;
...
}
...
}

a variable named amount local to the ifs block


and a parameter variable named amount.
39

VARIABLE SCOPE NESTED


BLOCKS

The scope of the parameter variable


amount is the entire function,
except the nested block.

Inside the nested block, amount


refers to the local variable that was
defined in that block.

You should avoid this potentially


confusing situation in the functions
that you write, simply by renaming
one of the variables.

40

GLOBAL VARIABLES

Global variables are defined outside any


block.

They are visible to every function defined


them.global variables are not a
after
Generally,
good idea.

But heres what they are and how to


use them
(if you must).
41

GLOBAL VARIABLES
In some cases, this is a good thing:
The <iostream> header defines these global
variables:
cin
cout
This is good because there should only be one of
each of these and every function who needs them should
have direct access to them.
42

GLOBAL VARIABLES
int balance = 10000; // A global variable
void withdraw(double amount)
{
if (balance >= amount)
{
balance = balance - amount;
}
}
int main()
{
withdraw(1000);
cout << balance << endl;
return 0;
}

When multiple
functions update
global variables,
the result can be
difficult to predict.
43

GLOBAL VARIABLES JUST


SAY NO

avoid

You should
global
variables in your programs!

44

PARAMETERS: REFERENCE &


Call by value
VALUES

Copy of data passed to function

Changes to copy do not change original

Used to prevent unwanted side effects

Call by reference
Function can directly access data

Changes affect original

& is used to signify a reference parameter


void change(int &variable){ variable += 3; }

45

void getData(int &p_id, string &p_name)


{
cout << Enter id:;
cin >> p_id;
cout << Enter last name:;
cin >> p_name;
}

int main()
{
int id;
string name;
getData(id,name);

The function updates two


values, id and name.
If we use return, only one
value can be returned.

cout << ID: " << id <<endl;


cout << "Name: " << name << endl;
return 0;
}

46

void swap(int &px, int &py)


{
int temp;
temp = px;
px = py;
py = temp;

int main()
}
{
int a = 10, b = 20;
swap(a,b);
cout << "Value of a is " << a <<endl;
cout << "Value of b is " << b << endl;
return 0;
}
47

Exercises
Consider the following function scramble():
void scramble (int i, int &j, int &k) {
i = 10; j = 20; k = 30;
}

What is the output of the following program fragment?


#include <iostream>

int main() {
int i=1, j=2, k=3;
scramble(i, j, k);
cout << i= << i << j=
<< j
<< k= << k <<
endl;
return 0;
}

#include <iostream>

int main() {
int i=1, j=2, k=3;
scramble(j, j, j);
cout << i= << i << j=
<< j
<< k= << k <<
endl;
return 0;
48
}

Exercises
What is the output of the following C++ program?
#include <iostream>
using namespace std;
int funny (int &a, int b) {
int c = a + b;
a = b; b = c;
return c; }
int main() {
int x = 3, y = 4, z = 5;
cout << funny(x, y) << endl;
cout << x= << x << y= << y << endl;
z = funny(x, z);
cout << z= << z << x= << x << endl;
return 0;
}
49

Exercises
Consider the following valid program:
#include <iostream>
using namespace std;
int main() {
int x = 1;
f(x);
cout << x= << x << endl;
return 0;
}

When the program runs, the output is:


x= 2

Write the function prototype for f().


50

SUMMARY

Understand the philosophy of Functions


Functions Constructs

Function Definitions

Function Header (Return-value-type, Function-name,


Parameter-list)
Function Body

Function Prototypes
Function Calls

A local variable and global variable


Function Overloading
Pass-by-value VS. Pass-by-reference

51

Vous aimerez peut-être aussi