Chapter 4 Methods - WordPress.com · function that does not return a value ... Its function...

Post on 18-Oct-2020

4 views 0 download

Transcript of Chapter 4 Methods - WordPress.com · function that does not return a value ... Its function...

LECTURE 6

BITG 1233: Function

(Part 1)

1 LECTURE 6

Learning Outcomes

At the end of this lecture, you should be able to:

explain the benefits of modular programming

describe the concept of a function

identify types of function

define function, declare function and call function

use actual parameter and formal parameter

differentiate function that returns a value and

function that does not return a value

identify local and global variables and their scope

2 LECTURE 6

Modular Programming Complex problems can be broken down into sub tasks, each of

which is easy to implement in C++.

Modular programming: breaking a program up into smaller,

manageable functions or modules.

Function: a block of statements in a program to perform a specific

task.

Motivation for modular programming:

Multiple programmers : each sub task, is easy to be implemented

by a programmer.

Easier readability, testing and maintenance : program is read,

tested and maintained based on its specific function.

Reduce duplication of code : functions can be called/used

repeatedly in a program, simplifies the process of writing programs.

3 LECTURE 6

4 LECTURE 6

Function Concept

5 LECTURE 6

• A function is to :

receive zero or more data

operate on the data; or just produce side effect (output);

or both

return at most one data value.

• Function definition: statements in program that describe

how a function will do its task.

• Function call: statement in program that causes a function

to execute, in order to get its task done.

6 LECTURE 6

Function Concept

Types of Function

There are 2 types of function :

Standard Library (or Pre-defined) Function

Programmer defined Function

In C++, a program contains numerous functions :

main() : is a programmer defined function; it is a must and

can only be one in a program.

main() often call/use standard library functions.

main() can also call/use other programmer defined

functions.

A programmer defined function, can also call other

programmer defined functions.

7 LECTURE 6

Functions in a C++ program

8 LECTURE 6

Standard Library Function

Its function definition has been coded and kept in a file

called header file.

Programmer just need to know:

what the pre-defined function will do,

how to call it,

which header file to include.

9 LECTURE 6

Example : some of the pre-defined mathematical

functions in <cmath> are:

The power function, pow(x,y)

The square root function, sqrt(x)

The floor function, floor(x)

To make use of the function, programmer has to include the

header file in the program.

example : #include <cmath>

And, also call the function in the program.

example : pow(2,3)

LECTURE 6 10

Standard Library Function

Function

Explanation

Example

log( x )

Natural logarithm of x (base

of e)

log( 2.718282 ) is 1.0

log10( x )

Logarithm for x (based of 10)

log10( 100.0 ) is 2.0

pow( x, y )

x raised to the power y

pow(2.0,7) is 128

pow(9, 0.5) is 3

sin( x )

Trigonometric value of sine

for x (value is in radian)

sin(0.0) is 0

sqrt( x )

Non-negative square root of x

sqrt(400.00) is 20.0

tan( x )

Trigonometric value of

tangent for x (value is in

radian)

tan( 0.0 ) is 0

Standard library / Pre-defined function Some functions defined in <cmath> :

11 LECTURE 6

Pre-defined Functions – Program eg.

#include <iostream>

#include <cmath>

using namespace std;

int main()

{

double angle;

cout << ”input angle in radians: ”;

cin >> angle;

cout << ”\nthe sine of the angle is ” << sin(angle) << endl;

return 0;

}//end main

LECTURE 6 12

Programmer-Defined Function

Is a function that can be defined by the programmer to:

perform independent task,

receive zero or more duplicate value, (by using pass by

value)

receive zero or more address, (by using pass by

reference)

return at most a single value to the function calling

statement, and also

modify exiting data via the parameter list (by using pass

by reference)

To use this type of function, the programmer will have to call

(or invoke) the function. But the function must be defined

and also declared before it can be called.

13 LECTURE 6

A programmer defined

function consists of three

parts, and their order in a

program is as follows:

1. Function declaration /

function prototype

statements to notify the

compiler about a function

before making a call to the

function.

2. Function call (or

invocation)

3. Function definition

LECTURE 6 14

Programmer Defined Function

TIPS : The order of

program preparation for

the three parts should be

as follows :

1- First, write the function

definition. (Location:

after the definition of

**the calling function)

2- Then only we know how

to write the function

declaration (prototype),

3- and how to call the

function.

15 LECTURE 6

1

2

3

**function that calls another

function.

Programmer Defined Function

Function Definition

The code of instructions that describe how a function will do

its task.

Two parts : the function header and the function body

16 LECTURE 6

Function Definition: Function Header

Consist of : the return type, the function name and formal

parameter list

• Return type

The data type of a value that is returned to the program statement

that has made a call to the function. The data type of the

expression in the return statement must match the return type in the function header. For example void, int, char and double.

• Function name

A valid identifier is used as the function’s name.

• Formal Parameter List

List that defines and declares the variables that will keep the data

passed to the function. Each variables must be defined and

declared fully with multiple parameters separated by commas. 17

LECTURE 6

Function Definition: Function Body • Enclosed in { }.

• Contains : local declarations; and statements that perform the

function’s task.

• Start with local declarations that specify the variables required by

the function. The function’s statements, terminating with a return

statement are coded after local declarations.

18 LECTURE 6

About function definition

Function Declaration (Prototype)

• Consist of three parts : the return type, function name, and the

formal parameter list (same as in function header).

• Terminated with semicolon ( ; )

• Placed in global area of the program.

• Format: return_type function_name(parameter_list);

• Example :

double average (int x, int y);

double average (int, int);

void display ( );

char pilihan ( );

19 LECTURE 6

LECTURE 6 20

• Function calling statement : to call a function, use the function name followed by ( ) and ;

• Example :

printHeading();

cout << average ( 3, 7 );

avg = average ( z, x );

cout << average ( 3, 7 ) + 5;

Function Call

Function Parameter

• Actual parameters: expressions in the parentheses set ( ) of

the calling statement.

• Formal parameters: variables that are declared in the header

of the function definition.

• The formal and actual parameters must match exactly in

type, order and number. Their names however, do not need

to be the same.

21 LECTURE 6

22 LECTURE 6

Function Call - Flow of Control • When a function is

called, program executes the body of the called function.

• After the called function terminates, execution resumes in the calling function, at point of call.

Called Function

Function Call

Calling Function

x

y

Example of:

function definition and function call.

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

return value type function name formal parameters

return a value

function

body

function

header

parameter list

Define a function (named max) Call to function max

int k = max(x, y);

actual parameters

(or arguments)

23 LECTURE 6

#include <iostream>

using namespace std;

int max(int, int);

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

Function call - Trace the flow of

program control

24 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

i is now 5

25 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

j is now 2

26 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

Invoke max(i, j)

27 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

pass the value 5 to num1

pass the value 2 to num2

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

Invoke max(i, j)

Pass the value of i to num1

Pass the value of j to num2

28 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

Declare a variable named result

29 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

(num1 > num2) is true since

num1 is 5 and num2 is 2

30 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

result is now 5

31 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

return result, which is 5 to max(i,j)

32 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

max(i, j); assigns the returned

value that is 5 to k

33 LECTURE 6

Trace Function Invocation

int max(int num1, int num2)

{

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

int main()

{

int i = 5;

int j = 2;

int k = max(i, j);

cout << "The maximum between "

<< i <<" and "<< j << " is "<< k;

return 0;

}

Execute the print instruction

Output : The maximum between 5 and 2 is 5

34 LECTURE 6

Void functions with no parameters

;

Calling a function with no parameters

Output : Hello World!

Void function is a function that DOES NOT return a value.

< >

35 LECTURE 6

Void functions with parameters

Pass by Value

Calling a function with parameters

Output : 5 10

36 LECTURE 6

Functions that return value

Pass by Value

Output :

8 squared: 64

Returns the value of 8*8 that is 64 to function main, then assigns the value to b.

Calls

function

sqr by

copying

the

value of

a to x

37 LECTURE 6

Variable Scope • Scope determines the the part of program in which you can use

defined object.

• Global scope – any object defined in the global area of the

program is visible from its definition until the end of the program.

global variables : variables that are declared outside the

function, recognised by any function or program that start after

its declaration.

• Local scope – variable defined within a block, visible only in the

block in which they are declared.

local variables : variables that are declared in the function

body and can only be used in that particular function. Local

variables do not relate to any variable in other function.

Therefore can have the same name as variables in other

functions.

38 LECTURE 6

Local Variables

39 LECTURE 6

A function’s local variables exist only while the function is executing. This is known as the lifetime of a local variable.

When the function begins, its local variables and its parameter variables are created in memory, and when the function ends, the local variables and parameter variables are destroyed.

This means that any value stored in a local variable is lost between calls to the function in which the variable is declared.

You can declare a local variable with the same name multiple times in different non-nesting blocks in a function, but you cannot declare a local variable twice in nested blocks.

Local Variables A variable declared in the initial action part of a for loop

header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body

from its declaration and to the end of the block that contains the

variable.

void method1() {

.

.

for (int i = 1; i < 10; i++)

{

.

int j;

.

.

.

}

}

The scope of j

The scope of i

40 LECTURE 6

Local Variables

void function1()

{

int x = 1;

int y = 1;

for (int i = 1; i < 10; i++)

{

x += i;

}

for (int i = 1; i < 10; i++)

{

y += i;

}

}

It is legal to declare i in two

non-nesting blocks

void function2()

{

int i = 1;

int sum = 0;

for (int i = 1; i < 10; i++)

{

sum += i;

}

cout << i << endl;

cout << sum << endl;

}

It is illegal to

declare i in two nesting blocks

41 LECTURE 6

Global Variables

A global variable is any variable defined outside all the functions in a program.

The scope of a global variable is the portion of the program from the variable definition to the end.

This means that a global variable can be accessed by all functions that are defined after the global variable is defined.

Local variables do not have default values, but global variables are defaulted to zero.

You should avoid using global variables because they

make programs difficult to debug.

Any global that you create should be global constants.

42 LECTURE 6

#include <iostream>

using namespace std;

int y;

void t1();

void t2();

int main()

{

t1();

t2();

return 0;

}

void t1()

{

int x = 1;

cout << "x = " << x << endl;

cout << "y = " << y << endl<<endl;

x++;

y++;

}

void t2()

{

int x = 1;

cout << "x = " << x << endl;

cout << "y = " << y << endl<<endl;

}

Example of

Variable Scope

43 LECTURE 6

Unary Scope Resolution

If a local variable name is the same as a global variable name,

you can access the global variable using ::globalVariable.

The :: operator is known as the unary scope resolution. For

example, the following code:

44 LECTURE 6

Static Local Variables

After a function completes its execution, all its local variables are destroyed. Sometimes, it is desirable to retain the value stored in local variables so that they can be used in the next call. C++ allows you to declare static local variables. Static local variables are permanently allocated in the memory for the lifetime of the program. To declare a static variable, use the keyword static.

45 LECTURE 6

When ‘static’ is used

#include <iostream>

using namespace std;

void t1();

int main()

{

t1();

t1();

return 0;

}

void t1()

{

static int x = 1;

int y = 1;

x++;

y++;

cout << "x = " << x << endl;

cout << "y = " << y << endl << endl;

}

46 LECTURE 6

When ‘static’ is NOT used

#include <iostream>

using namespace std;

void t1();

int main()

{

t1();

t1();

return 0;

}

void t1()

{

int x = 1;

int y = 1;

x++;

y++;

cout << "x = " << x << endl;

cout << "y = " << y << endl << endl;

}

- THE END - 47 LECTURE 6