Introduction to Programming in C++
Eighth Edition
Chapter 9: Value-Returning Functions
© 2016 Cengage Learning®. May not be scanned, copied or
duplicated, or posted to a publicly accessible website, in whole
or in part.
Objectives
• Raise a number to a power using the pow function
• Return the square root of a number using the sqrt
function
• Generate random numbers
• Create and invoke a function that returns a value
• Pass information by value to a function
• Write a function prototype
• Understand a variable’s scope and lifetime
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 2
or in part.
Functions
• A function is a block of code that performs a task
• Every C++ program contains at least one function (main)
– Most contain many functions
• Some functions are built-in functions (part of C++):
defined in language libraries
• Others, called program-defined functions, are written
by programmers; defined in a program
• Functions allow for blocks of code to be used many
times in a program without having to duplicate code
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 3
or in part.
Functions (cont’d.)
• Functions also allow large, complex programs to be
broken down into small, manageable sub-tasks
• Each sub-task is solved by a function, and thus different
people can write different functions
• Many functions can then be combined into a single
program
• Typically, main is used to call other functions, but any
function can call any other function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 4
or in part.
Functions (cont’d.)
Figure 9-1 Illustrations of value-returning and void functions
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 5
or in part.
Value-Returning Functions
• All functions are either value-returning or void
• All value-returning functions perform a task and then
return precisely one value
• In most cases, the value is returned to the statement
that called the function
• Typically, a statement that calls a function assigns the
return value to a variable
– However, a return value could also be used in a
comparison or calculation or could be printed to the
screen
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 6
or in part.
The pow Function
• The pow function is a convenient tool to raise a number
to a power (exponentiation)
• The pow function raises a number to a power and returns
the result as a double number
• Syntax is pow(x, y), in which x is the base and y is the
exponent
• At least one of the two arguments must be a double
• Program must contain the #include <cmath>
directive to use the pow function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 7
or in part.
The pow Function (cont’d.)
Figure 9-2 How to use the pow function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 8
or in part.
The sqrt Function
• sqrt function is a built-in value-returning function that
returns a number’s square root as a double
• Definition contained in cmath library
– Program must contain #include <cmath> to use it
• Syntax: sqrt(x), in which x is a double or float
– Here, x is an actual argument, which is an item of
information a function needs to perform its task
• Actual arguments are passed to a function when called
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 9
or in part.
The sqrt Function (cont’d.)
Figure 9-3 How to use the sqrt function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 10
or in part.
The Hypotenuse Program
• Program that calculates and displays the length of a
right triangle hypotenuse
• Program uses Pythagorean theorem
– Requires squaring and taking square root
• pow function can be used to square
• sqrt function can be used to take square root
• Both are built-in value-returning functions
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 11
or in part.
The Hypotenuse Program
(cont’d.)
Figure 9-4 Pythagorean theorem
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 12
or in part.
The Hypotenuse Program
(cont’d.)
Figure 9-5 Problem specification, IPO chart information, and C++
instructions for the Hypotenuse Program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 13
or in part.
The Hypotenuse Program
(cont’d.)
Figure 9-6 Beginning of Hypotenuse program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 14
or in part.
The Hypotenuse Program
(cont’d.)
Figure 9-6 Completion of Hypotenuse Program and sample run
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 15
or in part.
The rand, srand, and time
Functions
• C++ provides a pseudo-random number generator
– Produces a sequence of numbers that meet certain
statistical requirements for randomness
– Numbers chosen uniformly from finite set of numbers
– Not truly random but sufficient for practical purposes
• Random number generator in C++: rand function
– Returns an integer between 0 and RAND_MAX, inclusive
– RAND_MAX is a built-in constant (>= 32767)
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 16
or in part.
The rand, srand, and time
Functions (cont’d.)
• rand function’s syntax: rand()
– Doesn’t require any actual arguments, but parentheses are
still required
• Expression:
lowerBound + rand() % (upperBound – lowerBound + 1)
– Allows ranges other than 0 to RAND_MAX to be used
– Range is upperBound to lowerBound
• Initialize random number generator each time
– Otherwise, will produce the same sequence
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 17
or in part.
The rand, srand, and time
Functions (cont’d.)
Figure 9-7 How to use the rand function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 18
or in part.
The rand, srand, and time
Functions (cont’d.)
Figure 9-8 How to generate random integers within a specific range
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 19
or in part.
The rand, srand, and time
Functions (cont’d.)
Figure 9-8 How to generate random integers within a specific range
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 20
or in part.
The rand, srand, and time
Functions (cont’d.)
• Use srand function (a void function) to initialize
random number generator
• Syntax: srand(seed), in which seed is an integer
actual argument that represents the starting point of
the generator
– Commonly initialized using the time function
• Ensures unique sequence of numbers for each program run
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 21
or in part.
The rand, srand, and time
Functions (cont’d.)
• time function is a value-returning function that
returns current time in number of seconds since
January 1, 1970
– Returns a time_t object, so must be cast to an integer
before passing to srand
– Program must contain #include <ctime> directive
to use it
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 22
or in part.
The rand, srand, and time
Functions (cont’d.)
Figure 9-9 How to use the srand function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 23
or in part.
The Guessing Game Program
• Program generates a random number from 1 to 10 and
then allows the user as many choices as needed to
guess the number.
• The srand, time, and rand functions are all utilized
in the program.
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 24
or in part.
The Guessing Game
Program(cont’d.)
Figure 9-10 Problem specification, IPO chart information, and C++
instructions for the Guessing Game Program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 25
or in part.
The Guessing Game
Program(cont’d.)
Figure 9-11 Guessing Game Program and sample run
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 26
or in part.
Creating Program-Defined Value-
Returning Functions
• A program-defined value-returning function definition is
composed of a header and a body
• Header (first line) contains return data type, name of
function, and an optional parameterList
– Rules for function names are same as for variables
– Good idea to use meaningful names that describe
function’s purpose
– Memory locations in parameterList are called formal
parameters
• Each stores an item of information passed to the function
when it is called
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 27
or in part.
Creating Program-Defined Value-
Returning Functions (cont’d.)
• Function body contains instructions for performing the
function’s assigned task
• Surrounded by braces ({})
• Last statement is usually the return statement
– Returns one value (must match return data type in
function header)
• After return statement is processed, program
execution continues in calling function
• Good idea to include comment (such as //end of
functionName) to mark end of function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 28
or in part.
Creating Program-Defined Value-
Returning Functions (cont’d.)
Figure 9-12 How to create a program-defined value-returning function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 29
or in part.
Creating Program-Defined Value-
Returning Functions (cont’d.)
Figure 9-12 How to create a program-defined value-returning function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 30
or in part.
Calling a Function
• A function must be called (invoked) to perform its task
• main is automatically called when program is run
• Other functions must be called by a statement
• Syntax for calling a function:
functionName([argumentList]);
– argumentList is list of actual arguments (if any)
– An actual argument can be a variable, named constant,
literal constant, or keyword
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 31
or in part.
Calling a Function (cont’d.)
• Value-returning functions are typically called from
statements that:
– Assign the return value to a variable
– Use the return value in a calculation or comparison
– Display the return value
• A call to a void function is an independent statement
because void functions do not return values
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 32
or in part.
Calling a Function (cont’d.)
• C++ allows you to pass either a variable’s value or its
address to a function
• Passing a variable’s value is referred to as passing by value
• Passing a variable’s address is referred to as passing by
reference
• Default is passing by value
• Number, data type, and ordering of actual arguments must
match the formal parameters in function header
– Names do not need to match (different names are better)
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 33
or in part.
Calling a Function (cont’d.)
Figure 9-13 How to call (invoke) a value-returning function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 34
or in part.
Calling a Function (cont’d.)
Figure 9-14 Function call and function definition
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 35
or in part.
The Savings Account Program
• The program allows the user to enter the initial deposit
made into a savings account and the annual interest rate.
• The program displays the amount of money in the
account at the end of 1 through 3 years, assuming no
additional deposits or withdrawals are made.
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 36
or in part.
The Savings Account Program
(cont’d.)
Figure 9-15 Problem specification, IPO chart information,
and C++ instructions for the Savings Account Program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 37
or in part.
The Savings Account Program
(cont’d.)
Figure 9-15 Problem specification, IPO chart information,
and C++ instructions for the Savings Account Program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 38
or in part.
The Savings Account Program
(cont’d.)
Figure 9-16 Flowcharts for the Savings Account Program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 39
or in part.
Function Prototypes
• When a function definition appears below the main
function, you must enter a function prototype above the
main function
• A function prototype is a statement that specifies the
function’s name, data type of its return value, and data
type of each of its formal parameters (if any)
– Names for the formal parameters are not required
• Programmers usually place function prototypes at
beginning of program, after the #include directives
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 40
or in part.
Function Prototypes (cont’d.)
Figure 9-17 How to write a function prototype
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 41
or in part.
Completing the Savings Account
Program
Figure 9-18 Savings Account Program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 42
or in part.
The Scope and Lifetime of a
Variable
• A variable’s scope indicates where in the program the
variable can be used
• A variable’s lifetime indicates how long the variable
remains in the computer’s internal memory
• Both scope and lifetime are determined by where you
declare the variable in the program
• Variables declared within a function and those that
appear in a function’s parameterList have a local scope
and are referred to as local variables
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 43
or in part.
The Scope and Lifetime of a
Variable (cont’d.)
• Local variables can be used only by the function in which
they are declared or in whose parameterList they appear
– Remain in internal memory until the function ends
• Global variables are declared outside of any function in
the program
– Remain in memory until the program ends
• Any statement can use a global variable
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 44
or in part.
The Scope and Lifetime of a
Variable (cont’d.)
• Declaring a variable as global can allow unintentional
errors to occur
– e.g., a function that should not have access to the variable
inadvertently changes the variable’s contents
• You should avoid using global variables unless necessary
• If more than one function needs to access the same
variable, it is better to create a local variable in one
function and pass it to other functions that need it
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 45
or in part.
Summary
• Functions
– Allow programmers to avoid duplicating code
– Allow for large, complex programs to be broken into
small, manageable tasks
• Some functions are built into the language, and others
are program-defined
• All functions are either value-returning or void
• A value-returning function returns one value
– Value returned to statement that called the function
• A void function returns no value
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 46
or in part.
Summary (cont’d.)
• Use the sqrt function to find the square root of a
number
• Use the pow function to raise a number to a power
• Items in parentheses in a function call are called actual
arguments
• The rand function is used to generate random
numbers
– Returns an integer between 0 and RAND_MAX
• srand function is used to initialize rand function
– time function usually used as seed (starting point)
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 47
or in part.
Summary (cont’d.)
• Function definition composed of header and body
• Header specifies function name, return data type, and
formal parameter names and types (if any)
– Data types and ordering of formal parameters must
match data types and ordering of actual arguments
• Body contains instructions for performing the function’s
assigned task
– Surrounded by braces ({})
• return statement returns the result of an expression
to the calling function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 48
or in part.
Summary (cont’d.)
• You call a function by including its name and actual
arguments (if any) in a statement
• Variables in C++ are passed by value by default
• A function prototype must be provided for each
function defined below the main function
• Scope of a variable indicates where in the program it
can be used
• Lifetime of a variable indicates how long it will stay in
internal memory
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 49
or in part.
Summary (cont’d.)
• Local variables can be used only within the function in
which they are declared or in whose parameterList they
appear
– Remain in memory until the function ends
• Global variables can be used anywhere
– Remain in memory until the program ends
• If more than one memory location have the same
name, position of the statement in which the name is
used determines which location is used
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 50
or in part.
Lab 9-1: Stop and Analyze
• Study the program in Figure 9-26, and then answer the
questions
Figure 9-26 Code for Lab 9-1
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 51
or in part.
Lab 9-1: Stop and Analyze
(cont’d.)
Figure 9-26 Code for Lab 9-1
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 52
or in part.
Lab 9-2: Plan and Create
Figure 9-27 Problem specification for Lab 9-2
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 53
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-27 Problem specification for Lab 9-2
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 54
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-28 IPO chart for the main function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 55
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-28 IPO chart for the main function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 56
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-29 IPO chart for the getPayment function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 57
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-29 IPO chart for the getPayment function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 58
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-31 IPO chart information and C++ instructions
for the main function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 59
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-32 IPO chart information and C++ instructions
for the getPayment function
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 60
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-34 Beginning of finalized Car Payment Program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 61
or in part.
Lab 9-2: Plan and Create (cont’d.)
Figure 9-34 Completion of finalized Car Payment Program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 62
or in part.
Lab 9-3: Modify
• Modify the program in Lab9-2.cpp. Make the changes
listed in Figure 9-35 below. Save the modified program
as Lab9-3.cpp
• Save, run, and test the program.
Figure 9-35 Modifications for Lab 9-3
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 63
or in part.
Lab 9-4: What’s Missing?
• The program is this lab should display the total due,
given the quantity purchased and the item price.
• Follow the instructions for starting C++ and opening the
Lab9-4.cpp file. Put the C++ instructions in the proper
order, and then determine the one or more missing
instructions.
• Test the program appropriately.
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 64
or in part.
Lab 9-5: Desk-Check
• Use the data shown in Figure 9-36 to desk-check the
figure’s code. What current total will the code display
on the screen?
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 65
or in part.
Lab 9-5: Desk-Check (cont’d.)
Figure 9-36 Test data and code for Lab 9-5
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 66
or in part.
Lab 9-6: Debug
• Test the program in the Lab9-6.cpp file using the data
20500, 3500, and 10 as the asset cost, salvage value, and
useful life, respectively.
• The depreciation should be $1700.00
• Debug the program
© 2016 Cengage Learning®. May not be scanned, copied or
An Introduction to Programming with C++, Eighth Edition duplicated, or posted to a publicly accessible website, in whole 67
or in part.