PROGRAMMER DEFINED FUNCTIONS
1
Programming Problems
• For Starters (Beginners and Intermediate)
– http://adriann.github.io/programming_problems.html
• University of Virginia Programming Competition Site
(Intermediate and Advanced)
– https://
uva.onlinejudge.org/index.php?option=com_onlinejudge&Item
id=8
• Project Eular (Intermediate and Advanced)
– https://projecteuler.net/archives
• Repository of sites containing Programming Problems
– http://
programmers.stackexchange.com/questions/756/where-can-i-f
ind-programming-puzzles-and-challenges
2
3
Coffee Machine as a ‘Blackbox’
4
Programmer-Defined Functions
• Two components of a function definition
– Function declaration (or function prototype)
• Shows how the function is called
• Must appear in the code before the function can be called
• Syntax:
Type_returned Function_Name(Parameter_List);
//Comment describing what function does ;
– Function definition
• Describes how the function does its task
• Can appear before or after the function is called
• Syntax:
Type_returned Function_Name(Parameter_List)
{
//code to make the function work
}
5
Function Declaration
• Tells the return type
• Tells the name of the function
• Tells how many arguments are needed
• Tells the types of the arguments
• Tells the formal parameter names
– Formal parameters are like placeholders for the actual
arguments used when the function is called
– Formal parameter names can be any valid identifier
• Example:
double total_cost(int number_par, double price_par);
// Compute total cost including 5% sales tax on
// number_par items at cost of price_par each
6
Example Function
7
Function Definition
• Provides the same information as the declaration
• Describes how the function does its task
function header
• Example:
double total_cost(int number_par, double price_par)
{
const double TAX_RATE = 0.05; //5% tax
double subtotal;
subtotal = price_par * number_par;
return (subtotal + subtotal * TAX_RATE);
}
function body
9
The Return Statement
• Ends the function call
• Returns the value calculated by the function
• Syntax:
return expression;
– expression performs the calculation
or
– expression is a variable containing the
calculated value
• Example:
return subtotal + subtotal * TAX_RATE;
10
The Function Call
• Tells the name of the function to use
• Lists the arguments
• Is used in a statement where the returned
value
makes sense
• Example:
double bill = total_cost(number, price);
11
Function Call Details
• The values of the arguments are plugged into
the formal parameters (Call-by-value mechanism
with call-by-value parameters)
– The first argument is used for the first formal
parameter, the second argument for the second
formal parameter, and so forth.
– The value plugged into the formal parameter is used
in all instances of the formal parameter in the
function body
12
Alternate Declarations
• Two forms for function declarations
– List formal parameter names
– List types of formal parmeters, but not names
– First aids description of the function in comments
• Examples:
double total_cost(int number_par, double price_par);
double total_cost(int, double);
• Function headers must always list formal
parameter names!
13
Order of Arguments
• Compiler checks that the types of the arguments
are correct and in the correct sequence.
• Compiler cannot check that arguments are in the
correct logical order
• Example: Given the function declaration:
char grade(int received_par, int min_score_par);
int received = 95, min_score = 60;
cout << grade( min_score, received);
– Produces a faulty result because the arguments are not in
the correct logical order. The compiler will not catch this!
14
Function Definition Syntax
• Within a function definition
– Variables must be declared before they are used
– Variables are typically declared before the
executable statements begin
– At least one return statement must end the
function
• Each branch of an if-else statement might have its
own return statement
15
Placing Definitions
• A function call must be preceded by either
– The function’s declaration
or
– The function’s definition
• If the function’s definition precedes the call, a
declaration is not needed
• Placing the function declaration prior to the
main function and the function definition
after the main function leads naturally to
building your own libraries in the future.
16
Procedural Abstraction
• The Black Box Analogy
– A black box refers to something that we know how
to use, but the method of operation is unknown
– A person using a program does not need to know
how it is coded
– A person using a program needs to know what the
program does, not how it does it
• Functions and the Black Box Analogy
– A programmer who uses a function needs to know
what the function does, not how it does it
– A programmer needs to know what will be produced if the
proper arguments are put into the box
17
Information Hiding
• Designing functions as black boxes is an
example of information hiding
– The function can be used without knowing how
it is coded
– The function body can be “hidden from view”
18
Function Implementations
and The Black Box
• Designing with the black box in mind allows us
– To change or improve a function definition without
forcing programmers using the function to change
what they have done
– To know how to use a function simply by reading the
function declaration and its comment
19
Procedural Abstraction and C++
• Procedural Abstraction is writing and using
functions as if they were black boxes
– Procedure is a general term meaning a “function like”
set of instructions
– Abstraction implies that when you use a function as
a black box, you abstract away the details of the
code in the function body
20
Procedural Abstraction and Functions
• Write functions so the declaration and comment
is all a programmer needs to use the function
– Function comment should tell all conditions
required of arguments to the function
– Function comment should describe the returned
value
– Variables used in the function, other than the
formal parameters, should be declared in the
function body
21
Formal Parameter Names
• Functions are designed as self-contained modules
• Different programmers may write each function
• Programmers choose meaningful names for
formal parameters
– Formal parameter names may or may not match
variable names used in the main part of the program
– It does not matter if formal parameter names
match other variable names in the program
– Remember that only the value of the argument is
plugged into the formal parameter
22
Use Pseudocode
• Pseudocode is a mixture of English and the
programming language in use
• Pseudocode simplifies algorithm design by
allowing you to ignore the specific syntax of
the programming language as you work out
the details of the algorithm
– If the step is obvious, use C++
– If the step is difficult to express in C++, use English
23
Local Variables
• Variables declared in a function:
– Are local to that function, they cannot be used
from outside the function
– Have the function as their scope
• Variables declared in the main part of a
program:
– Are local to the main part of the program, they
cannot be used from outside the main part
– Have the main part as their scope
24
Global Constants
• Global Named Constant
– Available to more than one function as well as the
main part of the program
– Declared outside any function body
– Declared outside the main function body
– Declared before any function that uses it
• Example: const double PI = 3.14159;
double volume(double);
int main()
{…}
– PI is available to the main function
and to function volume
25
Global Variables
• Global Variable -- rarely used when more
than one function must use a common
variable
– Declared just like a global constant except const is
not used
– Generally make programs more difficult to
understand and maintain
26
Formal Parameters
are Local Variables
• Formal Parameters are actually variables that are
local to the function definition
– They are used just as if they were declared in the
function body
– Do NOT re-declare the formal parameters in the
function body, they are declared in the function
declaration
• The call-by-value mechanism
– When a function is called the formal parameters
are initialized to the values of the
arguments in the function call
27
Example: Factorial
• n! Represents the factorial function
• n! = 1 x 2 x 3 x … x n
• The C++ version of the factorial function
– Requires one argument of type int, n
– Returns a value of type int
– Uses a local variable to store the current product
– Decrements n each time it
does another multiplication
n * n-1 * n-2 * … * 1
28
Overloading Function Names
• C++ allows more than one definition for the
same function name
– Very convenient for situations in which the “same”
function is needed for different numbers or types
of arguments
• Overloading a function name means providing
more than one declaration and definition using
the same function name
29
Overloading Examples
• double ave(double n1, double n2)
{
return ((n1 + n2) / 2);
}
• double ave(double n1, double n2, double n3)
{
return (( n1 + n2 + n3) / 3);
}
– Compiler checks the number and types of arguments
in the function call to decide which function to use
cout << ave( 10, 20, 30);
uses the second definition
30
Overloading Details
• Overloaded functions
– Must have different numbers of formal
parameters
AND / OR
– Must have at least one different type of
parameter
– Must return a value of the same type
31
Automatic Type Conversion
• Given the definition
double mpg(double miles, double gallons)
{
return (miles / gallons);
}
what will happen if mpg is called in this way?
cout << mpg(45, 2) << “ miles per gallon”;
• The values of the arguments will automatically be
converted to type double (45.0 and 2.0)
32
Type Conversion Problem
• Given the previous mpg definition and the
following definition in the same program
int mpg(int goals, int misses)
// returns the Measure of Perfect Goals
{
return (goals – misses);
}
what happens if mpg is called this way now?
cout << mpg(45, 2) << “ miles per gallon”;
– The compiler chooses the function that matches parameter
types so the Measure of Perfect Goals will be calculated
Do not use the same function name for unrelated functions
33
Formal Parameters
are Local Variables
• Formal Parameters are actually variables that are
local to the function definition
– They are used just as if they were declared in the
function body
– Do NOT re-declare the formal parameters in the
function body, they are declared in the function
declaration
• The call-by-value mechanism
– When a function is called the formal parameters
are initialized to the values of the
arguments in the function call
34
Overloading Function Names
• C++ allows more than one definition for the
same function name
– Very convenient for situations in which the “same”
function is needed for different numbers or types
of arguments
• Overloading a function name means providing
more than one declaration and definition using
the same function name
35
Overloading Examples
• double ave(double n1, double n2)
{
return ((n1 + n2) / 2);
}
• double ave(double n1, double n2, double n3)
{
return (( n1 + n2 + n3) / 3);
}
– Compiler checks the number and types of arguments
in the function call to decide which function to use
cout << ave( 10, 20, 30);
uses the second definition
36
Overloading Details
• Overloaded functions
– Must have different numbers of formal parameters
and/or
– Must have at least one different type of
parameter
– Must return a value of the same type
37
void-Functions
• In top-down design, a subtask might produce
– No value (just input or output for example)
– One value
– More than one value
• We have seen how to implement functions that
return one value
• A void-function implements a subtask that
returns no value or more than one value
38
void-Function Definition
• Two main differences between void-function
definitions and the definitions of functions
that return one value
– Keyword void replaces the type of the value returned
• void means that no value is returned by the function
– The return statement does not include an expression
• Example:
void show_results(double f_degrees, double c_degrees)
{
using namespace std;
cout << f_degrees
<< “ degrees Fahrenheit is euivalent to “ << endl
<< c_degrees << “ degrees Celsius.” << endl;
return;
}
39
Using a void-Function
• void-function calls are executable statements
– They do not need to be part of another statement
– They end with a semi-colon
• Example:
show_results(32.5, 0.3);
NOT: cout << show_results(32.5, 0.3);
40
void-Function Calls
• Mechanism is nearly the same as the function
calls we have seen
– Argument values are substituted for the formal
parameters
• It is fairly common to have no parameters in
void-functions
– In this case there will be no arguments in the function call
– Statements in function body are executed
– Optional return statement ends the function
• Return statement does not include a value to return
• Return statement is implicit if it is not included
41
Example:
Converting Temperatures
• The functions just developed can be used in a
program to convert Fahrenheit temperatures to
Celcius using the formula
C = (5/9) (F – 32)
– Do you see the integer division problem?
42
void-Functions
Why Use a Return?
• Is a return-statement ever needed in a
void-function since no value is returned?
– Yes!
• What if a branch of an if-else statement requires
that the function ends to avoid producing more
output, or creating a mathematical error?
43
The Main Function
• The main function in a program is used like a
void function…do you have to end the program
with a return-statement?
– Because the main function is defined to return a
value of type int, the return is needed
– C++ standard says the return 0 can be omitted, but
many compilers still require it
44
Call-by-Reference Example
• void get_input(double& f_variable)
{
using namespace std;
cout << “ Convert a Fahrenheit temperature”
<< “ to Celsius.\n”
<< “ Enter a temperature in Fahrenheit: “;
cin >> f_variable;
}
• ‘&’ symbol (ampersand) identifies f_variable as a
call-by-reference parameter
– Used in both declaration and definition!
45
Call-By-Reference Details
• Call-by-reference works almost as if the
argument variable is substituted for the formal
parameter, not the argument’s value
• In reality, the memory location of the argument
variable is given to the formal parameter
– Whatever is done to a formal parameter in the
function body, is actually done to the value at the
memory location of the argument variable
46
Call Comparisons
Call By Reference vs Value
• Call-by-reference • Call-by-value
– The function call: – The function call:
f(age);
Memory f(age);
Name Location Contents
age 1001 34
initial 1002 A
hours 1003 23.5
1004
void f(int var_par);
– void f(int& ref_par);
47
Example: swap_values
• void swap(int& variable1, int& variable2)
{
int temp = variable1;
variable1 = variable2;
variable2 = temp;
}
• If called with swap(first_num, second_num);
– first_num is substituted for variable1 in the parameter list
– second_num is substituted for variable2 in the parameter list
– temp is assigned the value of variable1 (first_num) since the
next line will loose the value in first_num
– variable1 (first_num) is assigned the value in variable2 (second_num)
– variable2 (second_num) is assigned the original value of
variable1 (first_num) which was stored in temp
48
Mixed Parameter Lists
• Call-by-value and call-by-reference parameters
can be mixed in the same function
• Example:
void good_stuff(int& par1, int par2, double& par3);
– par1 and par3 are call-by-reference formal parameters
• Changes in par1 and par3 change the argument variable
– par2 is a call-by-value formal parameter
• Changes in par2 do not change the argument variable
49
Choosing Parameter Types
• How do you decide whether a call-by-reference
or call-by-value formal parameter is needed?
– Does the function need to change the value of the
variable used as an argument?
– Yes? Use a call-by-reference formal parameter
– No? Use a call-by-value formal parameter
50
51
Inadvertent Local Variables
• If a function is to change the value of a variable
the corresponding formal parameter must be a
call-by-reference parameter with an ampersand
(&) attached
• Forgetting the ampersand (&) creates a
call-by-value parameter
– The value of the variable will not be changed
– The formal parameter is a local variable that has no
effect outside the function
– Hard error to find…it looks right!
52