Professional Documents
Culture Documents
Chapter 6 - Function
Chapter 6 - Function
FUNCTION
MODULAR PROGRAM
• In a modular program, codes are divided into some logical group
called modules.
• Each module will perform a specific task. To enable the module to
perform its task, the module must be called.
• A module is also known as a function. By having functions in our
program, we can easily control the flow of data and control,
especially for a complex software system.
• There are 2 types of functions:
Predefined function
User defined function
PREDEFINED FUNCTIONS
• A collection of functions and other program elements obtained
from C++ Standard Library function, accessible through header
files.
• Examples :
conio.h = getch( )
1. abs(12)
2. pow(3,3)
3. pow(4,2)
4. sqrt(49)
5. sqrt(25)
6. floor(36.27)
7. ceil(18.3)
Let’s Try !
Write each of the following as a C++ expression:
9²
√81
-b + √ b² - 4ac
2a
USER DEFINED FUNCTION
● User defined function is the function written by programmer to
perform certain task which is not available in C++ Standard
Library Functions.
● User defines function are classified into 2 categories:
Value-returning function – function that have a return type.
These function return a value of a specific data type using the
return statement.
Void function – function that do not have a return type. These
function do not use return statement to return a value.
USER DEFINED FUNCTION
Value-returning function
● Items to be considered:
if(x >= y)
max = x;
else
max = y;
return max;
} function return value
USER DEFINED FUNCTION
• Function definition are divided into two definition:
Formal parameter
A variable declared in the function heading.
Syntax: Formal parameter list
dataType identifier, dataType identifier, ……….
Actual parameter
A variable or expression listed in a call to a function.
Syntax: Actual parameter list
expression or variable, expression or variable, ……….
USER DEFINED FUNCTION
Function Prototype
● When you attach & after the dataType in the formal parameter list of a
function, the variable following that dataType become reference parameter.
USER DEFINED FUNCTION
Parameter Types
Static variable
• A variable for which memory remain allocated as long as the
program executes.
• Example are global variable.
• Declare static variable with static reserve word.
• Syntax : static dataType identifier;
USER DEFINED FUNCTION
Function Overloading
• Examples:
void functionXYZ ( )
void functionXYZ (int x, int y)
void functionXYZ (int one, float y)
void functionXYZ (int x, float y, char name)
Let’s Try !
i. funcDefaultParam ( );
ii.funcDefaultParam ( 2.8 );
iii.funcDefaultParam ( 3.2, 0, ‘h’ );
iv.funcDefaultParam ( 9.2, ‘*’ );
v. funcDefaultParam ( 7, 3 );