You are on page 1of 43

7

ER
PT N
S

H A IO
T
C UN C
F
OVERVIEW
 Introduction to function
 Types of variable and its scope - block, local & global.
 Predefined functions
 Independent Functions
 Functions data type
 Functions with parameter
 Value
 Reference
INTRODUCTION TO FUNCTION
 A complex problem is often easier to solve by dividing it into several
smaller parts each of which can be solved by itself.

 This is called top-down programming

 These parts are called functions in C++ (also sometimes called


subprograms)
WHAT IS A FUNCTION?
 a mini-program containing algorithms to do a specific task

 A function could be invoked (called) many times through its name (to
execute its task), by the main function or other functions

 When a function is invoked, the computer will execute all the instructions
in the function from start to end, and then it goes to the instruction after the
function call
ADVANTAGES OF FUNCTIONS
 Separate the concept (what is done) from the implementation (how it is
done)

 Make programs easier to understand

 Make programs easier to modify

 Can be called several times in the same program, allowing the code to be
reused.
INTRODUCING FUNCTION
 Function definition is a description of subprogram that contains :
 Function header : defines the return type, function name and list of
parameters. It similar to function prototype, except that the header does not
end with semicolon.
 Function body : contains declaration of local variables and executable
statements.
 A function is written once in the program and can be used by any other
function in the program.
 The function definition is placed either before the main() or after the main()
INTRODUCING FUNCTIONS
 A function is a collection of statements that are grouped together to perform
an operation.
Define a function Invoke a function

return value type method name formal parameters

function int z = max(x, y);


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

return result; return value


}
INTRODUCING FUNCTIONS
 Function signature is the combination of the function name and the
parameter list.
 The variables defined in the function header are known as formal
parameters.
 When a function is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument.
 A Function may return a value. The returnValueType is the data type of the
value the function returns.
 If the function does not return a value, the returnValueType is the keyword
void.
SCOPE OF VARIABLES
 A local variable: a variable defined inside a function.
 Scope: the part of the program where the variable can be referenced.
 The scope of a variable starts from its declaration and continues to the end
of the block that contains the variable
 You can declare a local variable with the same name in different blocks.
SCOPE OF 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 .
.
}
}
SCOPE OF VARIABLES

It is fine to declare i in two It is not good practice 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; }
}
}
LOCAL VARIABLES & GLOBAL
VARIABLES
Local variables
 used only inside that function that are declared them.
 Local variables do not have default values, but global variables are
defaulted to zero.
Global variables :
 When variable is declared as global variable, its value can be changed
anywhere during the program execution. It is because the value can be access
by all functions defines in the program.
 Global variable is declared outside any function in a program.
FUNCTIONS CLASSIFICATION
2 types of functions :-
 Predefined function or built-in or library function
 Independent function or user-defined function
PREDEFINED FUNCTIONS
 Functions that are ready-made by the producer of a compiler and stored in
the header files (.h) called libraries

 To use the predefined function, the appropriate library file must be included
in the preprocessor directive (# include)

 Common header files are :-


 a) iostream.h b) iomanip.h c) string.h
 d) char.h e) math.h f) stdlib.h
PREDEFINED FUNCTIONS
iostream.h

Name Description
cin Will pause the program to allow the
user to enter the data.
cout Output to the computer screen

iomanip.h

Name Description
setw(n) Set the field width to n
setprecision(n) Set the decimal point precision to n
places
setioflags(ios::fixed) Display the number in conventional
fixed-point decimal notation
setiosflags(ios::showpoint) Display a decimal point of that number
PREDEFINED FUNCTIONS
string.h

Name Description
strcpy(a,b) Copies b string into a string
strcmp(a,b) Compares a string with b string
strlen(a) Calculate the length of a string
strcat(a,b) Appends a string to b string
PREDEFINED FUNCTIONS
char.h/ctype.h

Name Description
toupper(c) Convert character c from lowercase to uppercase
tolower(c) Convert character c from uppercase to lowercase
isupper(c) Return true if c is an uppercase
islower(c) Return true if c is a lowercase
isdigit(c) Return true if c is a digit
isalpha(c) Return true if c is an alphanumeric
isspace(c) Return true if c is a space character
PREDEFINED FUNCTIONS

#include<iostream,h>
#include<char.h>
Input is K
void main(){
Enter one character :
char letter; K
cout<<“Enter one character : ”<<endl;
cin>>letter;
character is uppercase
if(isupper(letter)){ character K in lowercase is k
cout<<“character is uppercase”<<endl;
cout<<“character ”<<letter<<“ in
lowercase is ”<<tolower(letter); Input is k
}
else Enter one character :
cout<<“not uppercase letter”; k
}
not uppercase letter
PREDEFINED FUNCTIONS
math.h

Name Description
pow(x,y) Return x raised to the power of y
sqrt(x) Square root of x

stdlib.h

Name Description
abs(i) Convert to the absolute value of i
rand() Generate a random positive integer between
0 and RAND_MAX(32767)
srand(seed) Initialize random number generator where
seed represent the starting point for th rand
function
PREDEFINED FUNCTIONS

#include<iostream.h>
#include<math.h>
#include<stdlib.h>

void main()
{
cout<<“2 power of 3 = “<<pow(2,3);
cout<<endl;
cout<<“square root of 9 is =”<<sqrt(9)<<endl;
cout<<“absolute number of 3.5 is ”<<abs(3.5);
}

Output
2 power of 3 = 8
square root of 9 is 3
absolute number of 3.5 is 3
PREDEFINED FUNCTIONS

#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>

void main()
{ unsigned seed;
float randValue;
cout<<“Enter the value of seed”;
cin>>seed;
srand(seed);
cout<<“\n 5 random generated numbers are : \n”;
for (int i; i<=5; i++)
{
randValue = rand();
cout<<set(8)<<randValue<<endl;
}
}
INDEPENDENT FUNCTIONS
 functions written by the programmer
 the way the functions are used (called) is the same as library functions
 to use a function, only the prototype and a description on what the
function does is sufficient
 3 requirements to use the independent function :-
a) Function prototype declaration
b) Function call
c) Function definition
PROGRAM STRUCTURE
Basically, the overall program when using independent function are shown as
below:
#include<iostream.h>

Function prototype declaration; 1

void main(){

variable declaration;
statements / function calls; 2
}

Function definition(){ 3
statements;
}
FUNCTION PROTOTYPE DECLARATION
 Function prototype declaration is a function declaration before used in the
program.
 It allows the compiler to check for the existence of the function parameter
list and the return type is correct
 It placed before the main program.

 Syntax:-
Return_type Name_of_function (type_of_parameters);

1 2 3
FUNCTION PROTOTYPE DECLARATION

1 Return type
Indicates the type of value that the function will return to the caller
The return value may be: int, double, float, char, void
 void is used when the function does not return any value to the caller

2 Name Of Function
Function name must follow the rules in naming identifier.

3 Parameter Type

Indicates the type of parameters value that will receive by function


definition when the function is called.
Tells the caller the order of the value transmitted to the called function
It can contains more than one data type.
FUNCTION PROTOTYPE DECLARATION
void display ( );
 Declares the function display() does not receive any argument and does not
return any argument to the calling function

int findSum(int, int);


 Declares that the function findSum() expects to receive two integer
arguments and will return an integer value to the calling function

float swap (float, float, int, char);


 Declares that the function swap() requires 4 arguments – two float, one
integer, one char. This function will return a floating-point value.
FUNCTION CALL
 Function call is made to execute the statements in the Function definition.
 It placed in main function or in another function definition.
 When a function is called, the program control is passed to the called function
and the statements inside the function will be executed to the end until control is
passed back to the calling function.
 To call a function, specify the function name and the values of parameter that
the function needs to do it task. The paramater in function call is “actual
parameter”.
FUNCTION CALL
Syntax :
Function-name(actual parameters)

Name of function must similar with Number of parameter must be the same with the
the number of paramater in prototype
name of function in function prototype
Example of function calls : findMin(num1, num2);
When making a function call, there are two possibilities that must be
considered:
 Function call without return value
 Function call with return value
FUNCTION CALL
 Function call without return value : does not return any value to the
calling function

Prototype: void calculation (int);

float area; Note :The actual parameter must have a value


int number;
cin>>number;

Function Call

calculation (number);
FUNCTION CALL
Function call with return value
 This type of function will return a value to the calling function (function
call).
 After completing the last statement in function definition, the control
program is passed back to the calling function with a value to calling
function. This value will be used in the calling function.
There are four ways to call a function with return value:-
1) In an arithmetic expression
2) In a logical expression
3) In an assignment statement
4) In an output statement
PARAMETERS
Two types of parameters :
 Format parameter – define at the function header
 Actual parameter – define at function call that consists of parameter, variable
or expression.
RULES FOR PARAMETER PASSING
 The type of actual must be the same with the formal parameter.

 The order of parameter must be the same (first actual parameter


corresponds to the first formal parameter).

 The number of actual parameter must be the same with the number of
formal parameter.
TYPES OF INDEPENDENT FUNCTIONS
1. Function with no return value and no parameter

Function Prototype Function Call Function Definition

void display(); { …. void display()


….. {
display(); cout << “This is only a title of the program”<<
….. endl;
} }
void { …. void calcAreaCircle()
calcAreaCircle(); …. { double radius;
cin >> radius;
calcAreaCircle(); area = radius * radius * 3.142;
….. cout << “The area of circle is “<< area;
} }
EXAMPLE FUNCTION 1
Input radius : 7

#include<iostream.h>
main

void calcAreaCircle();

void main(){ calcAreaCircle();


calcAreaCircle();
}

calcAreaCircle
void calcAreaCircle()
{ double radius, area;
7 153.96
cin >> radius;
area = radius * radius * 3.142; radius area
cout << “The area of circle is “<<
area;
}
TYPES OF INDEPENDENT FUNCTIONS
2. Function with no return value and has parameter
Function Prototype Function Call Function Definition

void average(int, { int x, y; void average(int a, int b)


int); cin >> x >> y; { int avg;
average(x, y); avg = (a + b)/2;
….. cout << “The average is “ << avg;
} }
void factorial(int); { int x; void factorial(int a)
factoria(x); { int result=1;
…. while (a > 0)
} { result = result * a;
a = a – 1;
}
cout << “The factorial of “ << a << “is “ <<
result;
}
EXAMPLE FUNCTION 2.

Input x: 6, y:8
#include<iostream.h>
main
void average(int, int);

void main(){ 6 8
int x, y; x y
cin >> x >> y;
average(x, y);
} average

void average(int a, int b) 6 8 7


{ int avg;
a b avg
avg = (a + b)/2;
cout << “The average is “ << avg;
}
TYPES OF INDEPENDENT FUNCTIONS
3. Function with return value and no parameter

Function Prototype Function Call Function Definition

float areaCircle(); { double area; Float areaCircle()


area = { double radius;
areaCircle(); cin >> radius;
cout << “Area is A = 3.142 * radius * radius;
“ << area; return A;
} }
EXAMPLE FUNCTION 3

#include<iostream.h> Input radius: 7

float areaCircle(); main

void main(){ 153.96


double area;
area
area = areaCircle();
cout << “Area is “ << area;
} areaCircle
float areaCircle()
{ double radius,A; 153.96
7 153.96
cin >> radius;
radius A
A = 3.142 * radius * radius;
return A;
}
TYPES OF INDEPENDENT FUNCTIONS
4. Function with return value and has parameter

Function Prototype Function Call Function Definition

int factorial(int); { int x, fac; int factorial(int a)


cin >> x; { int result=1;
fac = while (a > 0)
factorial(x); { result = result * a;
cout << fac; a = a – 1;
} }
return result;
}
int average(int, int); { int x, y; int average(int a, int b)
cin >> x >>y; { int purata;
cout << “The purata = (a + b)/2;
average of the 2 return purata;
numbers is “ << }
average(x, y);
}
EXAMPLE FUNCTION 4.

#include<iostream.h> Input x: 2, y : 4

int average(int, int); main

void main(){ 2 4
int x, y;
x y
cin >> x >>y;
cout << “The average of the 2
numbers
average
is “ << average(x, y);
} 2 4 3
a b purata
int average(int a, int b)
{ int purata;
purata = (a + b)/2;
return purata;
}
TYPES OF INDEPENDENT FUNCTIONS
5. Function with no return value and has a reference parameter
 reference parameter – used to return values as a return output to
called function.
 it is used where more than one value or variable need to be returned
to the called function.
TYPES OF INDEPENDENT FUNCTIONS

Function Prototype Function Call Function Definition

void swap(int &, int { int x, y; void swap(int &a, int &b)
&); cin >> x >>y; { int temp;
swap(x, y); temp = a;
} a = b;
b = temp;
}
void calc(int, int, int { int x, y, total; Void calc(int a, int b, int &jum, float &purata)
&, float &); float avg; {
cin >> x >>y; jum = a + b;
calc(x, y, total, purata = jum/2;
avg); }
}
EXAMPLE FUNCTION 5

Input x: 2, y : 4
#include<iostream.h>

main
void calc(int, int, int &, float &);

void main(){ 2 4 6
int x, y, total; x y total
float avg;
3
cin >> x >>y;
average
calc(x, y, total, avg);
} calc

void calc(int a, int b, int &jum, float


2 4
&purata)
{ a b
jum = a + b;
purata = jum/2;
}

You might also like