0% found this document useful (0 votes)
11 views

Chapter 5 - Functions

Uploaded by

2022850052
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Chapter 5 - Functions

Uploaded by

2022850052
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

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.

 Functions are commonly used to break a


problem down into small manageable pieces,
or modules.
3
INTRODUCTION
 So far you have used functions in two ways:
1. You have created a function called main
in every program you’ve written.
2. You have called library functions such as
pow() and sqrt().

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

Why use function?


It is more easily solved.

Function simplify programs. A function can be


written once to perform a specific task, and then
be executed anytime it is needed, known as code
reuse.
6
INTRODUCTION
 C++ is a function-based language.

 A large programming problem can be broken


up into separate modules or subroutines
called function.

 One of these functions must be called


main(). The main() function invokes and
controls the execution of other functions
within its scope.
7
INTRODUCTION
#include <iostream> function
void X(); prototype/
int Y(); declaration
int main()
{ main function
Framework

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

Predefined (built-in) Function

User Defined Function


9
INTRODUCTION

A program may be broken up


CONCEPT

into a set of manageable


functions, or modules. This is
called modular programming .
10
INTRODUCTION
(USER DEFINED FUNCTION)
Description: This program demonstrates simple
function.

#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

User Defined Type Function (UDT)


12
USER DEFINED FUNCTION
(FUNCTION PROTOTYPE)
 Before the compiler encounters a call to a
particular function, it must already know
certain things about the function.
 It must know the number of parameters the
function uses, the type of each parameter, and
the return type of the function.
 One way of ensuring that the compiler has this
required information is to place the function
definition before all calls to that function.
 If not, we have to write the function prototype
first.
13
USER DEFINED FUNCTION
(FUNCTION PROTOTYPE)
 Syntax:

returnDataType functionName (Parameter list);

Note:
Ending with semicolon (;)
 Example:

double calcDiscount(double rate);


14
USER DEFINED FUNCTION
(FUNCTION DEFINITION)
 The programmer must first define a function
before we can use it in a program.
 Syntax:

returnDataType function_name
(parameter-list)
{
variable declaration

return expression;
}
15
USER DEFINED FUNCTION
(FUNCTION DEFINITION)
 All function definitions have the following parts:

• Every function must have a name. Same rules that


Function

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.

• The body of a function is the set of statements that


Body carry out the task the function is performing. These
statements are enclosed in a set of braces.

• A function can send a value back to the program


return data module that called it. The return type is the data
type type of the value being sent back.
16
USER DEFINED FUNCTION
(FUNCTION DEFINITION)
return data
type function parameter
name list (arguments)

function header int max (int num1, int num2)


Example

{
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

to the operating system.


 The return 0; statement causes the value
0 to be returned when the main function
finishes executing.
 Example:
int main ()
{
cout << "Hello World\n";
return 0;
}
18
USER DEFINED FUNCTION
(FUNCTION DEFINITION)
 Some functions simply perform one or more
statements and then return. (without return
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 main is called automatically when a


program starts, but all other functions must
be executed by function call statements.

 When a function is called, the program


branches to that function and executes the
statements in its body.
20
USER DEFINED FUNCTION
(FUNCTION CALLING)
 Syntax:

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).

max (num1, num2);


21
USER DEFINED FUNCTION
(FUNCTION CALLING)
// This program has two functions: main and displayMessage.
#include <iostream>
using namespace std;

/***************************************
* 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)

Component Purpose Example

Declaration Specifies function name, argument void func(int);


(Prototype) types, and return value. Alerts Or
compiler (and programmer) that a void func(int x);
function is coming up later.

Call Causes the function to be executed. func(10);

Definition The function itself. Contains the lines void func(int x) {


of code that constitute the function. //lines of code
}

header First line of definition. void func(int x)


23
ELIMINATING THE
DECLARATION
 You have to place the function definition (the
function itself), before the first call to the function.
 This approach is simpler for short programs, but it is
less flexible.
 Example:
void displayMessage () You have to write
{
Function definition
cout << “Enjoy yourself!!!”);
} FIRST!

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

cos(x) strcmp(str1,str2) toupper(ch)

pow(x,y) strcpy(destStr, srcStr) tolower(ch)

sqrt(x) strlen(str) isupper(ch)

 But when we write our own functions, the


declaration and definition are part of our
source file.
26
PARAMETER PASSING
 Values that are sent into a function are called
arguments.

 A parameter is a special variable that holds a


value being passed as an argument into a
function.

 By using parameters, you can design your own


functions that accept data.
27
PARAMETER PASSING
Notice: The integer variable definition
inside the parentheses

void displayValue(int num)


{
Example

cout << "The value is " << num << endl;


}

 The variable num is a parameter. This enables


the function displayValue to accept an
integer value as an argument.
28
PARAMETER PASSING
(PASS-BY-VALUE)
 Parameter purposes is to hold the information
passed to them by the arguments, which are
listed inside the parentheses of a function
call.
 Normally when information is passed to a
function it is passed by value.
 This means the parameter receives a copy of
the value that is passed to it.
 If a parameter’s value is changed inside a
function, it has no effect on the original
argument.
29
PASS-BY-VALUE
(EXAMPLE)
Description:Demonstrates that changes to a function
parameter have no effect on the original argument.
//#include <iostream>
using namespace std;
// Function Prototype
void changeMe(int aValue);
Example

int main()
{
int number = 12;

// Display the value in number


cout << "In main number is " << number << endl;
// Passing the value in number as an argument
changeMe(number);
// Display the value in number again
cout << "Back in main again, number is still "
<< number << endl;
return 0;
}
30
PASS-BY-VALUE
/*************************************
* This function changes the value *
* stored in its parameter myValue *
*************************************/
void changeMe(int myValue)
{
Example

// Change the value of myValue to 0


myValue = 0;

// Display the value in myValue


cout << "In changeMe, the value has been changed to “
<< myValue << endl;
}

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

in the changeMe function, the argument number is not


modified.
 This occurs because the myValue variable contains only a
copy of the number variable. Just this copy is changed, not
the original.

 The changeMe function does not have access to the


original argument.
32
PASS-BY-VALUE

When an argument is passed into a


parameter by value, only a copy of
CONCEPT

the argument’s value is passed.


Changes to the parameter do not
affect the original argument.
33
RETURNING A VALUE FROM
A FUNCTION
 Functions that return a value are known as
value-returning functions.
 Although several arguments can be passed
into a function, only one value can be
returned from it.
34
DEFINING A VALUE RETURN
FUNCTION
 When you are writing a value-returning
function, you must decide what type of value
the function will return.
 This is because you must specify the data type
of the return value in the function header and
function prototype.
 A value returning function, uses int,
double, bool, char or any other valid
data type in its header.
35
DEFINING A VALUE RETURN
FUNCTION
int sum(int num1, int num2)
{
int result;
result = num1 + num2;
Example

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

// Set the numeric output formatting


cout << fixed << showpoint << setprecision(2);
37
DEFINING A VALUE RETURN
FUNCTION
// Get the radius of the circle
cout << "This program calculates the area of a
circle.\n";
radius = getRadius();

// Caclulate the area of the circle


Example

area = PI * square(radius);

// Display the area


cout << "The area is " << area << endl;
return 0;
}
38
DEFINING A VALUE RETURN
FUNCTION
/********************************************
* This function returns the circle radius *
* input by the user. *
********************************************/
double getRadius()
{
Example

double rad;

cout << "Enter the radius of the circle: ";


cin >> rad;
return rad;
}
39
DEFINING A VALUE RETURN
FUNCTION
/*********************************************
* This function returns the square of the *
* double argument sent to it *
*********************************************/
double square(double number)
{
Example

return number * number;


}

Program Output with Example Input Shown in Bold


This program calculates the area of a circle.
Enter the radius of the circle: 10
The area is 314.16
40
DEFINING A VALUE RETURN
FUNCTION
main()
{
Calling Function

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;
} }

Program Output with Example Input Shown in Bold


This program calculates the area of a circle.
Enter the radius of the circle: 10
The area is 314.16
41
PASS-BY-VALUE
Description: This is a modular, menu-driven program
that computes health club membership fees.

#include <iostream>
#include <iomanip>
#include <string>
Example

using namespace std;


STEP 1: Function
// Function prototypes
void displayMenu();
Prototype
int getChoice();
void showFees(string category, double rate, int months);

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 << "\n Health Club Membership Menu\n\n";


cout << "1. Standard Adult Membership\n";
cout << "2. Child Membership\n";
cout << "3. Senior Citizen Membership\n";
cout << "4. Quit the Program\n\n";
}
44
PASS-BY-VALUE
/**************************************************
* This function inputs, validates, and returns *
* the user's menu choice.
*
**************************************************/
int getChoice()
{
int choice;
Example

cin >> choice;


while (choice < 1 || choice > 4)
{
cout << "The only valid choices are 1-4. Please re-
enter. ";
cin >> choice;
}
return choice;
}
45
PASS-BY-VALUE
/**************************************************************
* This function uses the membership type, monthly rate, and *
* number of months passed to it as arguments to compute and *
* display a member's total charges. It then holds the screen *
* until the user presses the ENTER key. This is necessary *
* because after returning from this function the displayMenu *
* function will be called, and it will clear the screen. *
**************************************************************/
void showFees(string memberType, double rate, int months)
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

Program Output with Example Input Shown in Bold


Health Club Membership Menu
1. Standard Adult Membership
Example

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.

 They are hidden from the statements in other


functions, which normally cannot access
them.
48
VARIABLES CONCEPT
(LOCAL VARIABLE)
Description: This program shows that variables
defined in a function are hidden from other
functions.
#include <iostream>
using namespace std;
Example

void anotherFunction(); // Function prototype

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

using namespace std;

// 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

totalPay; // Total pay

// Get the number of hours worked


cout << "How many hours did you work? ";
cin >> hours;

// Get the amount of base pay


basePay = getBasePay(hours);

// Get overtime pay, if any


if (hours > BASE_HOURS)
overtimePay = getOvertimePay(hours);
57
VARIABLES CONCEPT
(GLOBAL VARIABLE)
// Calculate the total pay
totalPay = basePay + overtimePay;

// Display the pay


Example 2

cout << setprecision(2) << fixed << showpoint;


cout << "Base pay RM" << setw(7) << basePay << endl;
cout << "Overtime pay RM" << setw(7) << overtimePay << endl;
cout << "Total pay RM" << setw(7) << totalPay << endl;
return 0;
}
58
VARIABLES CONCEPT
(GLOBAL VARIABLE)
/***************************************************************
* This function uses the hours worked value passed in to *
* compute and return an employee's pay for non-overtime hours.*
***************************************************************/
double getBasePay(double hoursWorked)
Example 2

{
double basePay;

if (hoursWorked > BASE_HOURS)


basePay = BASE_HOURS * PAY_RATE;
else
basePay = hoursWorked * PAY_RATE;

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;

if (hoursWorked > BASE_HOURS)


{
overtimePay = (hoursWorked-BASE_HOURS) *
PAY_RATE*OT_MULTIPLIER;
}
else
overtimePay = 0.0;

Program Output with Example Input Shown in Bold


return overtimePay;
} How many hours did you work? 48
Base pay RM 902.00
Overtime pay RM 270.60
Total pay RM1172.60
60
VARIABLES CONCEPT

A local variable is defined inside a


function and is not accessible outside the
CONCEPT

function. A global variable is defined


outside all functions and is accessible to
all functions in its scope.
61
CREATING USER DEFINED
FUNCTION
#include <iostream>
#include <math>
#include <conio>
using namespace std;

//Function prototype
Example

int sum( int , int );


int multiply (int , int );
int power ( int , int );
void maximum ( int , int );
void minimum ( int , int );

int main()
{ int num1, num2;

cout << "Enter two numbers: ";


cin >> 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 );

int valuePower = power( num1 , num2 );


cout << "\nThe value of power : "
<< valuePower;
Example

maximum ( num1 , num2 );


minimum ( 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

int power ( int x, int y )


{
return pow( x , y );
}

void maximum ( int x, int y )


{
int max;
if ( x > y )
max = x;
else
max = y;

cout << "\nThe maximum value : " << max;


}
64
CREATING USER DEFINED
FUNCTION
void minimum ( int x, int y )
{
int min;

if ( x < y )
min = x;
Example

else
min = y;

cout << "\nThe minimum value : " << min;


}

Program Output with Example Input Shown in Bold


Enter two numbers: 2 4
The value of sum :6
The value of multiply : 8
The value of power : 16
The maximum value : 4
The minimum value : 2
65
PASS-BY-REFERENCE
 Sometimes, we want a function to be able to
change a value in the calling function (i.e., the
function that called it).

 This can be done by making the parameter a


reference variable.

 Reference variables are defined like regular


variables, except there is an ampersand (&)
between the data type and the name.
 Example: int &count;
66
PASS-BY-REFERENCE
 Example:

void doubleNum(int &refVar)


{
refVar *= 2;
}

NOTE: The variable refVar is


called “a reference to an int.”
67
PASS-BY-REFERENCE
 The prototype for a function with a reference
parameter must have an ampersand as well.

 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

void doubleNum (int &refVar)


{
refVar *= 2;
}
70
PASS-BY-REFERENCE

A reference variable is a variable that


references the memory location of
another variable. Any change made to
CONCEPT

the reference variable is actually made


to the one it references. Reference
variables are sometimes used as
function parameters.
WHEN TO PASS ARGUMENTS BY
71 REFERENCE AND WHEN TO PASS
ARGUMENTS BY VALUE

• When an argument is a constant. • Only variables can be passed by


• When a variable passed as an reference
argument should not have its • When two or more variables passed
value changed. This protects it as arguments to a function need to
from being altered. have their values changed by that
• When exactly one value needs to function
• When a copy of an argument cannot
be “sent back” from a function to
reasonably or correctly be made,
the calling routine. such as when the argument is a file
stream object.

By
By Value
Reference
72
COMPARING PASS-BY-VALUE
& PASS-BY-REFERENCE
#include <iostream>
using namespace std;

int squareByValue( int );


void squareByReference ( int & );

int main()
{
int x = 2, z = 4;

cout<<“ x = “ << x << “ before squareByValue\n”


<< “Value returned by squareByValue: “
<< squareByValue( x ) << endl;
cout<< “x = “ << x << “ after squareByValue\n” <<
endl;

cout<<“z = “ << z << “before squareByReference” <<


endl;
squareByReference( z );
cout<< “z = “ << z << “after squareByReference”<<
endl;
73
COMPARING PASS-BY-VALUE
& PASS-BY-REFERENCE
int squareByValue ( int a )
{
return a *= a; //caller’s argument not
modified
}

void squareByReference (int &cRef )


{
cRef *= cRef; // caller’s argument modified
}
Program Output
x = 2 before squareByValue
Value returned by squareByValue: 4
x = 2 after squareByValue

z = 4 before squareByValue
z = 16 after squareByReference
74
PREDEFINED FUNCTION
 C++ compilers include predefined function,
ready-to-use function to make programming
easier.

 The functions that come with your compiler


are called library function.

 Library functions are just like functions you


create and may be used in the same way. The
difference is that the source code for library
functions does not appear in your program.
75
PREDEFINED FUNCTION
 The prototypes for library functions are
provided to your program using the
#include compiler directive.
 Example:
#include <iostream>
#include <math>
using namespace std;
int main()
{
double base, exponent, answer;
cout << "Enter the base: ";
cin >> base;
cout << "Enter the exponent: ";
cin >> exponent;
answer=pow(base, exponent);//built-in function
cout << "The answer is: " << answer << endl;

return 0;
}
76 PREDEFINED FUNCTION
 Many C++ compilers provide basic math
function. The header file math.h

Function Prototype Description


abs int abs (int x) Returns the absolute
value of an integer
pow double pow (double Calculate x to the
x, double y) power of y
sqrt double sqrt (double Calculate the positive
x) square root of x)
77 PREDEFINED FUNCTION
 C++ also includes many functions for analyzing and
changing characters. The header file ctype.h.
Function Prototype Description
isupper int isupper (int c) Determines if a character is
uppercase.
islower int islower (int c) Determines if a character is
lowercase
isalpha int isalpha (int c) Determines if a character is a letter
(a-z, A-Z)
Isdigit int isdigit (int c) Determines if a character is a digit
(0-9)
toupper int toupper (int c) Converts a character to uppercase

tolower int tolower (int c) Converts a character to lowercase.


78
PREDEFINED FUNCTION
 We can control the precision of floating-point numbers, i.e., the
number of digits to the right of the decimal point, by using
setprecision stream manipulator. The header file iomanip.h
 Example:
#include <iostream>
#include <math>
#include <iomanip>
using namespace std;

void main()
{
double root = sqrt (2.0);
int places;

cout.setf(ios::showpoint);
cout.setf(ios::fixed);

cout << "\nPrecision set by the set” << “precision manipulator:\n";

for(places=0; places <= 9; places++)


cout<<setprecision (places) << root << '\n';
}
79
PREDEFINED FUNCTION
 The use left and right flags enable fields to be left-
justified with padding characters to the right, or right-
justified with padding characters to the left, respectively.
 setw stream manipulator to specify internal spacing.
The header file iomanip.h
 Example:
#include <iostream>
#include <iomanip>
using namsepace std;
int main()
{
cout << setw(10) << setiosflags( ios::right) << “123”
<< endl;
return 0;
}
80 PREDEFINED FUNCTION
 The string handling library provides many useful functions for
manipulating string data, comparing string and others. The
header file string.h.
Function Prototype Function description
char *strcpy (char *s1, Copies the string s2 into the character array s1. The
const char *s2) value of s1 is returned.
char *strcpy (char *s1, Copies at most n characters of the string s2 into the
const char *s2, size_t character array s1. the value of s1 is returned.
n)
int strcmp (const char Compares the string s1 to the string s2. The function
*s1, const char *s2) returns a value of 0, less 0, or greater than 0 if s1 is
equal, less than, or greater than s2, respectively.
int strcmp (const char Compares up to n characters of the string s1 to the
*si, const char *s2, string s2. The function return 0, less than 0 or greater
size_t n) than 0 if s1 is equal to, less than, or greater than s2,
81
PREDEFINED FUNCTION

#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

ptr = strcmp(buf2, buf1);


if (ptr > 0)
cout<<"buffer 2 is greater than buffer 1\n";
else
cout << "buffer 2 is less than buffer 1\n";

ptr = strcmp(buf2, buf3);


if (ptr > 0)
cout<<"buffer 2 is greater than buffer 3\n";
else
cout << "buffer 2 is less than buffer 3\n";

return 0;
}
The End

Q&A
83

You might also like