0% found this document useful (0 votes)
56 views59 pages

Chapter 5 Functions: Lecturer: Mrs Rohani Hassan

This document discusses functions in C++. It covers objectives like creating functions, passing arguments, pass by value vs reference, function overloading, function prototypes, default arguments, and header files. It defines what a function is and explains concepts like the function signature, formal and actual parameters, and return values. Examples are provided to demonstrate defining a simple max function and calling it to return the maximum of two integers.

Uploaded by

SK Kepong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views59 pages

Chapter 5 Functions: Lecturer: Mrs Rohani Hassan

This document discusses functions in C++. It covers objectives like creating functions, passing arguments, pass by value vs reference, function overloading, function prototypes, default arguments, and header files. It defines what a function is and explains concepts like the function signature, formal and actual parameters, and return values. Examples are provided to demonstrate defining a simple max function and calling it to return the maximum of two integers.

Uploaded by

SK Kepong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 59

Chapter 5 Functions

Lecturer: Mrs Rohani Hassan

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
1
Objectives
 To create functions, invoke functions, and pass arguments to a function
(§5.2-5.4).
 To understand the differences between pass-by-value and pass-by-
reference (§§5.5-5.6).
 To use function overloading and understand ambiguous overloading
(§5.7).
 To use function prototypes for declaring function headers (§5.8).
 To know how to use default arguments (§5.9).
 To create header files for reusing functions (§5.11).
 To determine the scope of local and global variables (§5.13).
 To develop applications using the C++ mathematical functions (§5.14).
 To design and implement functions using stepwise refinement (§5.15).
 (Optional) To improve runtime efficiency using inline functions (§5.16).

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
2
Introducing Functions
A function is a collection of statements that are
grouped together to perform an operation.
Define a function Invoke a funciton

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; return value
else
result = num2;

return result;
}

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
3
Introducing Functions, cont.
• 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.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
4
Introducing Functions, cont.
• 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.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
5
Calling Functions
Listing 5.1 Testing the max Function
This program demonstrates calling a Function
max to return the largest of the int values

TestMax Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
6
animation

Calling Functions, cont.

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
7
animation

Trace Function Invocation


i is now 5

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
8
animation

Trace Function Invocation


j is now 2

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
9
animation

Trace Function Invocation


invoke max(i, j)

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
10
animation

Trace Function Invocation


invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
11
animation

Trace Function Invocation


declare variable result

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
12
animation

Trace Function Invocation


(num1 > num2) is true since
num1 is 5 and num2 is 2

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
13
animation

Trace Function Invocation


result is now 5

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
14
animation

Trace Function Invocation


return result, which is 5

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
15
animation

Trace Function Invocation


return max(i, j) and assign the
return value to k

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
16
animation

Trace Function Invocation


Execute the print statement

pass the value i


pass the value 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 " result = num2;
<< k;
return 0; return result;
} }

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
17
Call Stacks

Space required for the


max function
result: 5
num2: 2
num1: 5
Space required for the Space required for the Space required for the
main function main funciton main function
k: k: k: 5 Stack is empty
j: 2 j: 2 j: 2
i: 5 i: 5 i: 5

(a) The main function (b) The max (c) The max function is (d) The main function
is invoked. function is invoked. finished and the return is finished.
value is sent to k.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
18
animation

Trace Call Stack


int main()
{ i is declared and initialized
int i = 5;
int j = 2;
int k = max(i, j);

cout << "The maximum between "


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

int max(int num1, int num2)


{
int result;
i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;

return result;
}

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
19
animation

Trace Call Stack


int main() j is declared and initialized
{
int i = 5;
int j = 2;
int k = max(i, j);

cout << "The maximum between "


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

int max(int num1, int num2)


{
j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
is invoked.
else
result = num2;

return result;
}

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
20
animation

Trace Call Stack


int main()
{
Declare k
int i = 5;
int j = 2;
int k = max(i, j);

cout << "The maximum between "


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

int max(int num1, int num2)


{ Space required for the
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
The main method
return result; is invoked.
}

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
21
animation

Trace Call Stack


int main()
{ Invoke max(i, j)
int i = 5;
int j = 2;
int k = max(i, j);

cout << "The maximum between "


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

int max(int num1, int num2)


{
int result; Space required for the
main method
if (num1 > num2) k:
result = num1; j: 2
else i: 5
result = num2;

return result; The main method


} is invoked.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
22
animation

Trace Call Stack


int main() pass the values of i and j to num1
{
int i = 5; and num2
int j = 2;
int k = max(i, j);

cout << "The maximum between "


<< i << " and " + j + " is "
<< k;
return 0;
}
num2: 2
int max(int num1, int num2)
num1: 5
{ Space required for the
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
23
animation

Trace Call Stack


int main()
{
(num1 > num2) is true
int i = 5;
int j = 2;
int k = max(i, j);

cout << "The maximum between "


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

result:
int max(int num1, int num2) num2: 2
{ num1: 5
int result;
Space required for the
main method
if (num1 > num2) k:
result = num1; j: 2
else i: 5
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
24
animation

Trace Call Stack


int main()
Assign num1 to result
{
int i = 5;
int j = 2;
int k = max(i, j);

cout << "The maximum between "


<< i << " and " + j + " is "
<< k; Space required for the
return 0; max method
} result: 5
num2: 2
num1: 5
int max(int num1, int num2)
{ Space required for the
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
25
animation

Trace Call Stack


int main() Return result and assign it to k
{
int i = 5;
int j = 2;
int k = max(i, j);

cout << "The maximum between "


<< i << " and " + j + " is "
<< k; Space required for the
return 0;
max method
}
result: 5
num2: 2
int max(int num1, int num2) num1: 5
{ Space required for the
int result;
main method
k:5
if (num1 > num2)
j: 2
result = num1;
else i: 5
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
26
animation

Trace Call Stack


int main()
{ Execute print statement
int i = 5;
int j = 2;
int k = max(i, j);

cout << "The maximum between "


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

int max(int num1, int num2)


{ Space required for the
int result; main method
k:5
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;

return result; The main method


} is invoked.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
27
void Functions
The preceding section gives an example of a
nonvoid function. This section shows how to
declare and invoke a void function. Listing 5.2
gives a program that declares a function named
printGrade and invokes it to print the grade for a
given score.

TestVoidFunction Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
28
Pass by Value
When you invoke a function with a parameter, the value of the
argument is passed to the parameter. This is referred to as pass-
by-value. If the argument is a variable rather than a literal value,
the value of the variable is passed to the parameter. The variable
is not affected, regardless of the changes made to the parameter
inside the function. We will examine an interesting scenario in
the following example, in which the parameters are changed in
the function but the arguments are not affected.

TestPassByValue Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
29
Pass by Value, cont.
The values of num1 and num2 are
passed to n1 and n2. Executing swap
does not affect num1 and num2.

Space required for the


swap function
temp:
n2: 2
n1: 1
Space required for the Space required for the Space required for the
main function main function main function Stack is empty
num2: 2 num2: 2 num2: 2
num1: 1 num1: 1 num1: 1

The main funciton The swap function The swap function The main function
is invoked is invoked is finished is finished

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
30
Reference Variables
C++ provides a special type of variable, called a reference
variable, which can be used as a function parameter to reference
the original variable. A reference variable is an alias for another
variable. Any changes made through the reference variable are
actually performed on the original variable. To declare a
reference variable, place the ampersand (&) in front of the name.
For example, see Listing 5.4.

TestReferenceVariable Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
31
Pass By Reference
You can use a reference variable as a parameter in a function
and pass a regular variable to invoke the function. The parameter
becomes an alias for the original variable. This is known as
pass-by-reference. When you change the value through the
reference variable, the original value is actually changed.

TestPassByReference Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
32
Overloading Functions
The max function that was used earlier works only
with the int data type. But what if you need to find
which of two floating-point numbers has the
maximum value? The solution is to create another
function with the same name but different
parameters, as shown in the following code:

TestFunctionOverloading Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
33
Ambiguous Invocation
Sometimes there may be two or more
possible matches for an invocation of a
function, but the compiler cannot determine
the most specific match. This is referred to
as ambiguous invocation. Ambiguous
invocation is a compilation error.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
34
Ambiguous Invocation
#include <iostream>
using namespace std;
int maxNumber(int num1, double num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
double maxNumber(double num1, int num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
int main()
{
cout << maxNumber(1, 2) << endl;
return 0;
}

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
35
Function Prototypes
Before a function is called, it must be declared first.
One way to ensure it is to place the declaration
before all function calls. Another way to approach
it is to declare a function prototype before the
function is called. A function prototype is a
function declaration without implementation. The
implementation can be given later in the program.

TestFunctionPrototype Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
36
Default Arguments
C++ allows you to declare functions with default
argument values. The default values are passed to
the parameters when a function is invoked without
the arguments.

DefaultArgumentDemo Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
37
Case Study: Computing Taxes
with Functions
The program in Listing 3.4, “Computing Taxes,” uses if
statements to check the filing status and computes the tax
based on the filing status. This example uses functions to
simplify Listing 3.4.
Each filing status has six brackets. The code for
computing taxes is nearly the same for each filing status
except that each filing status has different bracket ranges.
For example, the single filer status has six brackets [0,
6000], (6000, 27950], (27950, 67700], (67700, 141250],
(141250, 307050], (307050, ), and the married file jointly
status has six brackets [0, 12000], (12000, 46700], (46700,
112850], (112850, 171950], (171950, 307050], (307050,
).
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
38
Case Study cont.
The first bracket of each filing status is taxed at 10%, the second
15%, the third 27%, the fourth 30%, the fifth 35%, and the sixth
38.6%. So you can write a Function with the brackets as arguments to
compute the tax for the filing status. The signature of the Function is:
public static double computeTax(double income, 400000
int r1, int r2, int r3, int r4, int r5)

[0, 6000], (6000, 27950], (27950, 67700], (67700, 141250], (141250, 307050], (307050, )

For example, you can invoke computeTax(400000, 6000, 27950,


67700, 141250, 307050) to compute the tax for single filers with
$400,000 of taxable income:

ComputeTaxWithFunction Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
39
Reusing Functions by Different
Programs
One of the benefits of functions is for reuse. In the
preceding sections, you declared functions and used them
from the same program. To make the functions available
for other programs to use, you need to place the functions
in a separate file, called header file. By convention, the file
has a .h extension. Programs use #include preprocessor
directives to include header files in order to reuse the
functions defined in the header file.

MyLib.h UseMyLib.cpp Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
40
Case Study: Generating Random
Characters
Computer programs process numerical data and characters.
You have seen many examples that involve numerical
data. It is also important to understand characters and how
to process them.

As introduced in §2.11, every character has a unique


ASCII code between 0 and 127. To generate a random
character is to generate a random integer between 0 and
127. You learned how to generate a random number in
§3.8. Recall that you can use the srand(seed) function to
set a seed and use rand() to return a random integer. You
can use it to write a simple expression to generate random
numbers in any range. For example,
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
41
Case Study: Generating Random
Characters, cont.
Returns a random integer
rand() % 10
between 0 and 9.

50 + rand() % 50 Returns a random integer


between 50 and 99.

a + rand() % b Returns a random number between


a and a + b, excluding a + b.

RandomCharacter.h

TestRandomCharacter Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
42
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.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
43
Scope of Local Variables, cont.
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.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
44
Scope of Local Variables, cont.
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 .
.
}
}

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
45
Scope of Local Variables, cont.
It is fine 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; }
}
}

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
46
Global Variables
C++ also allows you to use global variables.
They are declared outside all functions and are
accessible to all functions in its scope. Local
variables do not have default values, but global
variables are defaulted to zero.

VariableScopeDemo Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
47
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:
#include <iostream>
using namespace std;
int v1 = 10;
int main()
{
int v1 = 5;
cout << "local variable v1 is " << v1 << endl;
cout << "global variable v1 is " << ::v1 << endl;
return 0;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
48
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.

StaticVariableDemo Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
49
Function Abstraction
You can think of the Function body as a black
box that contains the detailed implementation for
the Function.
Optional arguments Optional return
for Input value

Method Signature
Black Box
Method body

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
50
Benefits of Functions
• Write a Function once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
51
Math Functions
Function Description Example

abs(x) Returns the absolute value of the argument abs(-2) is 2


ceil(x) x is rounded up to its nearest integer and ceil(2.1) is 3
returns this integer ceil(-2.1) is -2
floor(x) x is rounded down to its nearest integer and floor(2.1) is 2
returns this integer floor(-2.1) is -3
exp(x) Returns the exponential function of x exp(1) is 2.71828
pow(x, y) Returns a raised to power b (xy) pow(2.0, 3) is 8
log(x) Returns the natural logarithm of x log(2.71828) is 1.0
log10(x) Returns the base-10 logarithm of x log10(10.0) is 1
sqrt(x) Returns the square root of x sqrt(4.0) is 2
sin(x) Returns the sine of x. x represents an angle sin(3.14159 / 2) is 1
in radians sin(3.14159) is 0
cos(x) Returns the cosine of x. x represents an cos(3.14159 / 2) is 0
angle in radians cos(3.14159) is -1
tan(x) Returns the tangent of x. x represents an tan(3.14159 / 4) is 1
angle in radians tan(0.0) is 0
fmod(x, y) Returns the remainder of x/y as double fmod(2.4, 1.3) is 1.1

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
52
Stepwise Refinement
The concept of Function abstraction can be applied
to the process of developing programs. When
writing a large program, you can use the “divide
and conquer” strategy, also known as stepwise
refinement, to decompose it into subproblems. The
subproblems can be further decomposed into
smaller, more manageable problems.

PrintCalendar

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
53
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate the
stepwise refinement approach.

December 2005
----------------------------------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Run

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
54
Design Diagram
printCalendar
(main)

readInput printMonth

printMonthTitle printMonthBody

getMonthName getStartDay

getTotalNumOfDays

getNumOfDaysInMonth

isLeapYear

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
55
Implementation: Top-Down
Top-down approach is to implement one Function in the
structure chart at a time from the top to the bottom. Stubs
can be used for the Functions waiting to be implemented.
A stub is a simple but incomplete version of a Function.
The use of stubs enables you to test invoking the Function
from a caller. Implement the main Function first and then
use a stub for the printMonth Function. For example, let
printMonth display the year and the month in the stub.
Thus, your program may begin like this:

A Skeleton for printCalendar

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
56
Implementation: Bottom-Up
Bottom-up approach is to implement one Function in the
structure chart at a time from the bottom to the top. For
each Function implemented, write a test program to test it.
Both top-down and bottom-up Functions are fine. Both
approaches implement the Functions incrementally and
help to isolate programming errors and makes debugging
easy. Sometimes, they can be used together.

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
57
Inline Functions
Implementing a program using functions makes the program easy to
read and easy to maintain, but function calls involve runtime overhead
(i.e., pushing arguments and CPU registers into the stack and
transferring control to and from a function). C++ provides inline
functions to avoid function calls. Inline functions are not called;
rather, the compiler copies the function code in line at the point of
each invocation. To specify an inline function, precede the function
declaration with the inline keyword, as shown in Listing 5.18.

InlineDemo Run

InlineDemo1

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
58
Short Functions
Not for long Functions
Compiler Decision
Inline functions are desirable for short functions, but not
suitable for long functions that are called in multiple
places in a program, because long inline functions will
dramatically increase the executable code size when it is
copied in multiple places. For this reason, C++ allows the
compilers to ignore the inline keyword if the function is
too long. So, the inline keyword is merely a request to the
compiler, and it is up for the compiler to make the
decision whether to honor it or ignore it.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
59

You might also like