Chapter 5 - Functions
Chapter 5 - Functions
By
En. Mohd Nizam bin Osman
Senior Lecturer
Department of Computer Science
Faculty of Computer and Mathematical Sciences
UiTM, Perlis
1
2
INTRODUCTION
A function is a collection of statements that
performs a specific task.
User
defined
Library function W il l l
function earn
Main
function
4
INTRODUCTION
(THE IDEA)
This program has one long, complex In this program the problem has been
function containing all of the statements divided into smaller problems, each
necessary to solve a problem. handled by a separate function.
5
INTRODUCTION
X();
Function’s
Y();
return 0; function
} calling
void X()
{ function
//statement definition
//statement
}
int Y()
{
//statement function
//statement definition
return value;
}
8
INTRODUCTION
In C++, we have two types of functions:
Functions
#include <iostream>
using namespace std;
Example
//Function prototypes
void message();
int main()
{
message();
}
void message()
{
cout << “Hello world….”;
}
11
INTRODUCTION
(USER DEFINED FUNCTION)
Function
Function Prototype
Definition
Function
Calling
Note:
Ending with semicolon (;)
Example:
returnDataType function_name
(parameter-list)
{
variable declaration
…
return expression;
}
15
USER DEFINED FUNCTION
(FUNCTION DEFINITION)
All function definitions have the following parts:
Function Definition
apply for variable name.
Name
• The parameter list is the list of variables that hold the
Parameter values being passed to the function. If no values are
list being passed to the function, its parameter list is
empty.
{
int result;
method body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
A function definition} consists of a function header and a
function body
17
USER DEFINED FUNCTION
(FUNCTION DEFINITION)
Most of the main function program, in your
textbook is declared to return an int value
void Function
value)
Example: void Function
void displayMessage ()
{
cout << "Hello from the function
displayMessage.\n";
}
19
USER DEFINED FUNCTION
(FUNCTION CALLING)
A function is executed when it is called.
function_name (exact-parameter-list)
Exact-parameter-list :- – arguments whose values
are to be passed as input to the corresponding
parameters in the called function. An argument
can be explicit value/constant value, a variable
name, an expression or another function call.
The number and type of the arguments must
Example: correspond to the number and type of the
parameters in the called function (function
definition).
/***************************************
* This function displays a greeting. *
***************************************/
Example
void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}
Program Output
/***************************************
Hello from main.
* main *
Hello from the function displayMessage.
***************************************/
Back in function main again.
int main()
{
cout << "Hello from main.\n";
displayMessage(); Function Calling
cout << "Back in function main again.\n";
return 0;
}
FUNCTION
22
(THE DIFFERENT FUNCTION
COMPONENTS)
int main()
{
displayMessage(); THEN, main method
return 0;
}
24
LIBRARY/PREDEFINED
FUNCTION
When we use a library function we don’t need
to write the declaration or definition.
Example: math.h, string.h,
ctype.h
What you have to do, just open the library
using preprocessor header.
Example:
#include <math.h>
25
LIBRARY/PREDEFINED
FUNCTION
Then, you can used predefined function:
math.h string.h ctype.h
int main()
{
int number = 12;
Program Output
In main number is 12
In changeMe, the value has been changed to 0
Back in main again, number is still 12
31
PASS-BY-VALUE
Even though the parameter variable myValue is changed
Example - Analysis
return result;
}
This statement causes the function sends the value of
the result variable back to the statement that
called the function.
A value-returning function must have a return
statement.
It can be any expression that has a value, such as a
variable, mathematical expression or constant value.
36
DEFINING A VALUE RETURN
FUNCTION
Description: This program demonstrates two value-
returning functions. The square function is called
in a mathematical statement.
#include <iostream>
#include <iomanip>
using namespace std;
Example
//Function prototypes
double getRadius();
double square(double number);
int main()
{
const double PI = 3.14159; // Constant for pi
double radius; // Holds the circle's radius
double area; // Holds the circle's area
area = PI * square(radius);
double rad;
radius = getRadius();
area = PI * square(radius);
Example
Return to
Function
Calling
Return to
Function
(100)
Calling Function
Calling
(10)
getRadius() square(number)
{ {
return rad; return number * number;
} }
#include <iostream>
#include <iomanip>
#include <string>
Example
int main()
{ // Constants for monthly membership rates
const double ADULT_RATE = 40.00,
SENIOR_RATE = 30.00,
CHILD_RATE = 20.00;
int choice, // Holds the user's menu choice
months; // Number of months being paid
// Set numeric output formatting
cout << fixed << showpoint << setprecision(2);
42
PASS-BY-VALUE
do {
displayMenu();
STEP 2: Calling
choice = getChoice(); // Assign choice with Function
the value returned
if (choice != 4) // If user does not want to quit, proceed
{
cout << "For how many months? ";
cin >> months;
Example
switch (choice)
{
case 1: showFees("Adult", ADULT_RATE, months);
break;
case 2: showFees("Child", CHILD_RATE, months);
break;
case 3: showFees("Senior",SENIOR_RATE,months);
}
}
} while (choice != 4);
return 0;
}
43
PASS-BY-VALUE
/**********************************************
* This function clears the screen and then *
* displays the menu choices. *
STEP 3: Function
**********************************************/
void displayMenu() Definition
{
system("cls"); // Clear the screen.
Example
{
cout << endl
<< "Membership Type : " << memberType << " "
<< "Number of months: " << months << endl
<< "Total charges : $" << (rate * months) << endl;
// Hold the screen until the user presses the ENTER key.
cout << "\nPress the Enter key to return to the menu. ";
cin.get(); // Clear the previous \n out of the input buffer
cin.get(); // Wait for the user to press ENTER
}
46
PASS-BY-VALUE
2. Child Membership
3. Senior Citizen Membership
4. Quit the Program
1
For how many months? 3
Membership Type : Adult Number of months: 3
Total charges : $120
Press the Enter key to return to the menu.
47
VARIABLES CONCEPT
(LOCAL VARIABLE)
Variables defined inside a function are local to
that function.
int main()
{
int num = 1;
Local variable
cout << "In main, num is " << num << endl;
anotherFunction();
cout << "Back in main, num is still " << num << endl;
return 0;
}
49
VARIABLES CONCEPT
(LOCAL VARIABLE)
/***************************************************************
* This function displays the value of its local variable num. *
***************************************************************/
void anotherFunction()
{
int num = 20;
Local variable
Example
cout << "In anotherFunction, num is " << num << endl;
}
Program Output
In main, num is 1
In anotherFunction, num is 20
Back in main, num is still 1
50
VARIABLES CONCEPT
(LOCAL VARIABLE LIFETIME)
A local variable exists only while the function it
is defined in is executing.
This is known as the lifetime of a local variable.
When the function begins, its parameter
variables and any local variables it defines are
created in memory, and when the function
ends, they are destroyed.
This means that any values stored in a
function’s parameters or local variables are
lost between calls to the function
VARIABLES CONCEPT
51
(INITIALIZING LOCAL VARIABLES
WITH PARAMETER VALUES)
It is possible to use parameter variables to
initialize local variables.
Sometimes this simplifies the code in a
function.
Example: the function’s parameters are used
to initialize the local variable result.
int sum(int num1, int num2)
{
int result = num1 + num2;
return result;
}
52
VARIABLES CONCEPT
(GLOBAL VARIABLE)
A global variable is any variable defined
outside all the functions in a program,
including main.
The scope of a global variable is the portion of
the program from the variable definition to
the end of the entire program.
This means that a global variable can be
accessed by all functions that are defined
after the global variable is defined.
53
VARIABLES CONCEPT
(GLOBAL VARIABLE)
Description: This program shows that a global
variable is visible to all functions that appear in
a program after the variable's definition.
#include <iostream>
using namespace std;
Example 1
Global variable
void anotherFunction(); // Function prototype
int num = 2;
int main()
{
cout << "In main, num is " << num << endl;
anotherFunction();
cout << "Back in main, num is " << num << endl;
return 0;
}
54
VARIABLES CONCEPT
(GLOBAL VARIABLE)
/***************************************************************
* This function changes the value of the global variable num. *
***************************************************************/
void anotherFunction()
{
Example 1
cout << "In anotherFunction, num is " << num << endl;
num = 50;
cout << "But, it is now changed to " << num << endl;
}
Program Output
In main, num is 2
In anotherFunction, num is 2
But, it is now changed to 50
Back in main, num is 50
55
VARIABLES CONCEPT
(GLOBAL VARIABLE)
Description: This program calculates gross pay. It
uses global constants.
#include <iostream>
#include <iomanip>
Example 2
// Global constants
const double PAY_RATE = 22.55; // Hourly pay rate
const double BASE_HOURS = 40.0; // Max non-overtime hours
const double OT_MULTIPLIER = 1.5; // Overtime multiplier
// Function prototypes
double getBasePay(double);
double getOvertimePay(double);
56
VARIABLES CONCEPT
(GLOBAL VARIABLE)
int main()
{
double hours, // Hours worked
basePay, // Base pay
overtimePay = 0.0, // Overtime pay
Example 2
{
double basePay;
return basePay;
}
59
VARIABLES CONCEPT
(GLOBAL VARIABLE)
/********************************************************
* This function uses the hours worked value passed in *
* to compute and return an employee's overtime pay. *
********************************************************/
double getOvertimePay(double hoursWorked)
{
Example 2
double overtimePay;
//Function prototype
Example
int main()
{ int num1, num2;
//calling function
int valueSum = sum( num1 , num2 );
cout << " \nThe value of sum : " << valueSum;
62
CREATING USER DEFINED
FUNCTION
cout << "\nThe value of multiply : "
<< multiply (num1 , num2 );
return 0;
}
//Function definition
int sum ( int x , int y )
{
return x + y ;
}
63
CREATING USER DEFINED
FUNCTION
int multiply ( int x , int y )
{
int value = x * y;
return value;
}
Example
if ( x < y )
min = x;
Example
else
min = y;
Example:
void doubleNum(int &refVar);
OR
void doubleNum(int &);
68
PASS-BY-REFERENCE
// Program uses a reference variable as a function parameter.
#include <iostream>
using namespace std;
// Function prototype. The parameter is a reference variable.
void doubleNum(int &refVar);
int main()
Example
{
int value = 4;
cout << "In main, value is " << value << endl;
cout << "Now calling doubleNum..." << endl;
doubleNum(value);
cout << "Now back in main, value is " << value << endl;
return 0;
}
69
PASS-BY-REFERENCE
/**************************************************************
* This function's parameter is a reference variable. The & *
* tells us that. This means it receives a reference to the *
* original variable passed to it, rather than a copy of that *
* variable's data. The statement refVar *= 2 is doubling the *
* data stored in the value variable defined in main. *
**************************************************************/
Example
By
By Value
Reference
72
COMPARING PASS-BY-VALUE
& PASS-BY-REFERENCE
#include <iostream>
using namespace std;
int main()
{
int x = 2, z = 4;
z = 4 before squareByValue
z = 16 after squareByReference
74
PREDEFINED FUNCTION
C++ compilers include predefined function,
ready-to-use function to make programming
easier.
return 0;
}
76 PREDEFINED FUNCTION
Many C++ compilers provide basic math
function. The header file math.h
void main()
{
double root = sqrt (2.0);
int places;
cout.setf(ios::showpoint);
cout.setf(ios::fixed);
#include <iostream>
#include <string.h>
using namespace std;
Example
int main()
{
char string[10];
char *str1 = "abcdefghi";
strcpy(string, str1);
cout << string;
return 0;
}
82
PREDEFINED FUNCTION
#include <iostream>
#include <string.h>
using namespace std;
int main(void)
{ char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc";
int ptr;
Example
return 0;
}
The End
Q&A
83