DITG 1113:: Function (Part 1)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

DITG 1113:

Function
(Part 1)
by: MARLIZA BINTI RAMLY (FTMK)

LECTURE 6 1
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

LECTURE 6 2
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.

LECTURE 6 3
LECTURE 6 4
Function Concept

LECTURE 6 5
Function Concept
• 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.

LECTURE 6 6
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.

LECTURE 6 7
Functions in a C++ program

LECTURE 6 8
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.

LECTURE 6 9
Standard Library Function
 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 / Pre-defined function
Some functions defined in <cmath> :

Function Explanation Example


log( x ) Natural logarithm of x (base log( 2.718282 ) is 1.0
of e)

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 sin(0.0) is 0


for x (value is in radian)

sqrt( x ) Non-negative square root of x sqrt(400.00) is 20.0

tan( x ) Trigonometric value of tan( 0.0 ) is 0


tangent for x (value is in
radian)

LECTURE 6 11
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.

LECTURE 6 13
Programmer Defined Function
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
2
TIPS : The order of program
preparation for the three
parts should be as follows :

3 1- First, write the function


definition. (Location: after
the definition of **the
calling function)
1 2- Then only we know how to
write the function
declaration (prototype),
3- and how to call the
function.

**function that calls another


LECTURE 6 function. 15
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.
LECTURE 6 17
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.

About function definition

LECTURE 6 18
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 ( );

LECTURE 6 19
Function Call
• 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;

LECTURE 6 20
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.

LECTURE 6 21
Function Call - Flow of Control
• When a function is
called, program executes
the body of the called Calling
function. Function

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

Called x
Function
y

LECTURE 6 22
Example of:
function definition and function call.
Define a function (named max) Call to function max
return value type function name formal parameters

function int k = max(x, y);


int max(int num1, int num2)
header
{
function actual parameters
int result; parameter list (or arguments)
body
if (num1 > num2)
result = num1;
else return a value
result = num2;

return result;
}

LECTURE 6 23
Function call - Trace the flow of program
control
#include <iostream>
using namespace std;
int max(int num1, int num2)
int max(int, int); {
int result;
int main()
{ if (num1 > num2)
int i = 5; result = num1;
int j = 2; else
int k = max(i, j); result = num2;

cout << "The maximum between " return result;


<< i <<" and "<< j << " is "<< k; }
return 0;
}

LECTURE 6 24
Trace Function Invocation
i is now 5

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 25
Trace Function Invocation
j is now 2

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 26
Trace Function Invocation
Invoke max(i, j)

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 27
Trace Function Invocation
Invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

pass the value 5 to num1

pass the value 2 to num2

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 28
Trace Function Invocation
Declare a variable named result

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 29
Trace Function Invocation
(num1 > num2) is true since
num1 is 5 and num2 is 2

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 30
Trace Function Invocation
result is now 5

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 31
Trace Function Invocation
return result, which is 5 to max(i,j)

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 32
Trace Function Invocation

max(i, j); assigns the returned


value that is 5 to k

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 33
Trace Function Invocation
Execute the print instruction

Output :
The maximum between 5 and 2 is 5

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i <<" and "<< j << " is "<< k; result = num2;
return 0;
} return result;
}

LECTURE 6 34
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

Output :
Calling a function with parameters 5 10
LECTURE 6 36
Functions that return value

Calls
function Pass by Value
sqr by
copying
the
value of
a to x Output :

8 squared: 64

Returns the value of 8*8 that is 64 to function main, then assigns the value to b.
LECTURE 6 37
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.

LECTURE 6 38
Local Variables
• 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.

LECTURE 6 39
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++)
{
The scope of i .
int j;
.
The scope of j .
.
}
}

LECTURE 6 40
Local Variables
It is legal to declare i in two It is illegal to
non-nesting blocks declare i in two nesting blocks

void function1() void function2()


{ {
int x = 1; int i = 1;
int y = 1; int sum = 0;

for (int i = 1; i < 10; i++) for (int i = 1; i < 10; i++)
{ {
x += i; sum += i;
} }

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


{ cout << sum << endl;
y += i; }
}
}

LECTURE 6 41
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.

LECTURE 6 42
#include <iostream>
using namespace std;

int y; Example of
void t1();
void t2();
int main()
{
Variable Scope
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;
}

LECTURE 6 43
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:

LECTURE 6 44
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.

LECTURE 6 45
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;
}

LECTURE 6 46
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 -
LECTURE 6 47

You might also like