This presentation is a part of the COP2272C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce students to the C++ language and the fundamentals of object orientated programming..
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
4.16.24 21st Century Movements for Black Lives.pptx
C++ Functions, Recursion, and Parameters
1. An Introduction To Software
Development Using C++
Class #20:
Functions, Recursion
2. 2 Types Of Function Parameters
• Value Parameters: When a function is called, the value of a
value parameter is copied into the corresponding formal
parameter. After the copying, there is no relationship
between the value parameter and the formal parameter.
Value parameters only provide a one-way link from the value
parameter to the formal parameter.
• Reference Parameter: The reference parameter received the
address (memory location) of the actual parameter. Reference
parameters can pass one or more values from a function and
can change the value of the actual parameter.
Image Credit: mathinsight.org
3. When Are Reference Parameters
Useful?
1. When the value of the actual parameter needs
to be changed
2. When you want to return more than one value
from a function (note that the return statement
can only return one value)
3. When passing the address would save memory
space and time relative to copying a large
amount of data.
Image Credit: www.amazon.com
4. How Do You Define A Reference
Parameter?
• When you attach a & after a data type for a variable name in
the formal parameter list of a function, the variable becomes
a reference parameter.
5. In Class Programming Challenge:
Drywall Calculations, Part II
• Your program will read in data on the dimensions of the rooms in the house being
built.
• All rooms will be rectangular, 10’ tall, and will be measured in meters
(1m = 3.28 ft).
• Your program will then convert the room measurements that are in meters to feet
using a single function with two reference parameters.
• This function will return two values, the room size in feet, using the two reference
parameters.
• Your program will print out: the room name, the room size in meters, and the
room size in feet.
Image Credit: www.1drywall.com
You must make your main function be the first function in your file.
1
6. Inline Functions
• Implementing a program as a set of functions is good from a software engineering
standpoint, but function calls involve execution-time overhead.
• C++ provides inline functions to help reduce function call overhead—especially for
small functions.
• Placing the qualifier inline before a function’s return type in the function definition
“advises” the compiler to generate a copy of the function’s body code in place
(when appropriate) to avoid a function call.
• The trade-off is that multiple copies of the function code are inserted in the
program (often making the program larger) rather than there being a single copy
of the function to which control is passed each time the function is called.
• The compiler can ignore the inline qualifier and typically does so for all but the
smallest functions.
5 Image Credit: www.iisa.org
7. Default Arguments
• It’s common for a program to invoke a function repeatedly with the same argument value
for a particular parameter.
• In such cases, you can specify that such a parameter has a default argument, i.e., a default value to be
passed to that parameter.
• When a program omits an argument for a parameter with a default argument in a function call, the
compiler rewrites the function call and inserts the default value of that argument.
• Default arguments must be the rightmost (trailing) arguments in a function’s parameter list.
• When calling a function with two or more default arguments, if an omitted argument is not the rightmost
argument in the argument list, then all arguments to the right of that argument also must be omitted.
• Default arguments must be specified with the first occurrence of the function name—typically, in the
function prototype.
• If the function prototype is omitted because the function definition also serves as the prototype, then the
default arguments should be specified in the function header.
• Default values can be any expression, including constants, global variables or function calls.
• Default arguments also can be used with inline functions
Image Credit: devblackops.io
8. Default Arguments
• The first call to boxVolume specifies no arguments, thus using all three default values of 1.
• The second call passes only a length argument, thus using default values of 1 for the width
and height arguments.
• The third call (line 20) passes arguments for only length and width, thus using a default value
of 1 for the height argument.
• The last call (line 24) passes arguments for length, width and height, thus using no default
values.
• Any arguments passed to the function explicitly are assigned to the function’s parameters
from left to right.
• Therefore, when boxVolume receives one argument, the function assigns the value of that
argument to its length parameter (i.e., the leftmost parameter in the parameter list).
• When boxVolume receives two arguments, the function assigns the values of those
arguments to its length and width parameters in that order.
• Finally, when boxVolume receives all three arguments, the function assigns the values of
those arguments to its length, width and height parameters, respectively.
6 Image Credit: www.mining.com
9. Unary Scope Resolution Operator
• It’s possible to declare local and global variables of the same name.
• C++ provides the unary scope resolution operator (::) to access a
global variable when a local variable of the same name is in scope.
• The unary scope resolution operator cannot be used to access a
local variable of the same name in an outer block.
• A global variable can be accessed directly without the unary scope
resolution operator if the name of the global variable is not the
same as that of a local variable in scope.
7 Image Credit: www.hitec-graduate-school.de
10. Recursion!
• Some problems are best solved by having a function call
itself.
• A recursive function is a function that calls itself, either
directly, or indirectly (through another function).
• Although many compilers allow function main to call itself,
the C++ standard document indicate that main should not
be called within a program or recursively. Its sole purpose is
to be the starting point for program execution.
Image Credit: mr-verb.blogspot.com
11. Recursive Problem-Solving Approaches
• A recursive function is called to solve a problem.
• The function knows how to solve only the simplest case(s),
or so-called base case(s).
• If the function is called with a base case, the function simply returns a result.
• If the function is called with a more complex problem, it typically divides the problem into
two conceptual pieces—a piece that the function knows how to do and a piece that it does
not know how to do.
• To make recursion feasible, the latter piece must resemble the original problem, but be a
slightly simpler or smaller version.
• This new problem looks like the original, so the function calls a copy of itself to work on the
smaller problem—this is referred to as a recursive call and is also
called the recursion step.
• The recursion step often includes the keyword return, because its result will be combined
with the portion of the problem the function knew how to solve to form the result passed
back to the original caller, possibly main
Image Credit: keenformatics.blogspot.com
13. Recursive Problem-Solving Approaches
• The recursion step executes while the original
call to the function is still “open,” i.e., it has not
yet finished executing.
• The recursion step can result in many more such recursive
calls, as the function keeps dividing each new subproblem with which the
function is called into two conceptual pieces.
• In order for the recursion to eventually terminate, each time the function
calls itself with a slightly simpler version of the original problem, this
sequence of smaller and smaller problems must eventually converge on
the base case.
• At that point, the function recognizes the base case and returns a result to
the previous copy of the function, and a sequence of returns ensues up
the line until the original call eventually returns the final result to main.
2 Image Credit: www.joedog.org
14. Another Recursion Example:
Fibonacci Series
• The Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, …
• Begins with 0 and 1 and has the property that each
subsequent Fibonacci number is the sum of the previous
two Fibonacci numbers.
• The Fibonacci series can be defined recursively as follows:
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n – 1) + fibonacci(n – 2)
3 Image Credit: en.wikipedia.org
16. A Note Of Caution About Recursion
• A word of caution is in order about recursive programs like the one we use here to
generate Fibonacci numbers.
• Each level of recursion in function fibonacci has a doubling effect on the number of
function calls; i.e., the number of recursive calls that are required to calculate the
nth Fibonacci number is on the order of 2n.
• This rapidly gets out of hand.
• Calculating only the 20th Fibonacci number would require on the order of 220 or
about a million calls, calculating the 30th Fibonacci number would require on the
order of 230 or about a billion calls, and so on.
• Computer scientists refer to this as exponential complexity.
• Problems of this nature humble even the world’s most
powerful computers!
Image Credit: en.wikipedia.org
17. Recursion vs. Iteration
• Both iteration and recursion are based on a control statement: Iteration uses a
repetition structure; recursion uses a selection structure.
• Both iteration and recursion involve repetition: Iteration explicitly uses a repetition
structure; recursion achieves repetition through repeated function calls.
• Iteration and recursion both involve a termination test: Iteration terminates when
the loop-continuation condition fails; recursion terminates when a base case is
recognized.
• Iteration with counter-controlled repetition and recursion both gradually approach
termination: Iteration modifies a counter until the counter assumes a value that
makes the loop-continuation condition fail; recursion produces simpler versions of
the original problem until the base case is reached.
• Both iteration and recursion can occur infinitely: An infinite loop occurs with
iteration if the loop-continuation test never becomes false; infinite recursion
occurs if the recursion step does not reduce the problem during each recursive
call in a manner that converges on the base case.
Image Credit: albello.com
18. Iterative solution
to the Factorial Problem
• A repetition statement is used rather than the selection
statement of the recursive solution.
• Both solutions use a termination test. In the recursive
solution, it tests for the base case. In the iterative solution,
it tests the loop-continuation condition—if
the test fails, the loop terminates.
• Finally, instead of producing simpler versions of the
original problem, the iterative solution uses a counter that
is modified until the loop-continuation condition becomes
false.
4 Image Credit: www.recommind.com
19. The Downside Of Recursion
• Recursion has negatives.
• It repeatedly invokes the mechanism, and consequently the
overhead, of function calls.
• This can be expensive in both processor time and memory space.
• Each recursive call causes another copy of the function (actually
only the function’s variables) to be created; this can consume
considerable memory.
• Iteration normally occurs within a function, so the overhead of
repeated function calls and extra memory assignment is omitted.
• So why choose recursion?
Image Credit: lawyernomics.avvo.com
20. Why Choose Recursion?
• Any problem that can be solved recursively can also be
solved iteratively (nonrecursively).
• A recursive approach is normally chosen when the
recursive approach more naturally mirrors the problem and
results in a program that’s easier to understand and debug.
• Another reason to choose a recursive solution is that an
iterative solution is not apparent.
• Avoid using recursion in performance
situations. Recursive calls take time and
consume additional memory.
Image Credit: everythingcomputerscience.com
21. Today’s In-Class
Programming Challenge: Phonewords
• Given a phone number, 800-356-9377, write a
recursive C++ program to generate as many words
out of these numbers as possible.
• 2 (a,b,c), 3 (d,e,f), 4(g,h,i), 5 (j,k,l), 6 (m,n,o),
7 (p,q,r,s), 8 (t,u,v), 9 (w,x,y,z)
• Ignore trying to convert
the “800” into a word.
Image Credit: www.acma.gov.au
22. What’s In Your C++ Toolbox?
cout / cin #include if/else/
Switch
Math Class String getline While
For do…While Break /
Continue
Arrays Functions
Hinweis der Redaktion
New name for the class
I know what this means
Technical professionals are who get hired
This means much more than just having a narrow vertical knowledge of some subject area.
It means that you know how to produce an outcome that I value.
I’m willing to pay you to do that.