Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lec05-06 (Topic 3 Functions) - v2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 139

1

LECTURE 5
Functions
Overview
5.1 Predefined and Programmer-Defined Functions
5.1.1 Predefined Functions
5.1.2 Functions Declaration
5.1.3 Function Definition
5.2 Local Variables
5.3 Overloading Function Names
5.4 void Functions
5.5 Passing Variables in Function
3

5.1
Predefined and Programmer-Defined Functions
Predefined Functions
• C++ comes with libraries of predefined functions

• Example: sqrt function


• the_root = sqrt(9.0);

• returns, or computes, the square root of a number

• The number, 9, is called the argument

• the_root will contain 3.0


Function Calls
• sqrt(9.0) is a function call
• It invokes, or sets in action, the sqrt function
• The argument (9), can also be a variable or an
expression

• A function call can be used like any expression


• bonus = sqrt(sales) / 10;
• Cout << “The side of a square with area ”
<< area << “ is ” << sqrt(area);
6
Function Call Syntax
• Function_name (Argument_List)
• Argument_List is a comma separated list:

(Argument_1, Argument_2, … , Argument_Last)

• Example:
• side = sqrt(area);

• cout << “2.5 to the power 3.0 is “


<< pow(2.5, 3.0);
Function Libraries
• Predefined functions are found in libraries

• The library must be “included” in a program to make the functions


available

• An include directive tells the compiler which library header file to


include.

• To include the math library containing sqrt():

#include <cmath>

• Newer standard libraries, such as cmath, also require the directive


using namespace std;
Other Predefined Functions
• abs(x) --- int value = abs(-8);
• Returns absolute value of argument x
• Return value is of type int
• Argument is of type x
• Found in the library cstdlib

• fabs(x) --- double value = fabs(-8.0);


• Returns the absolute value of argument x
• Return value is of type double
• Argument is of type double
• Found in the library cmath
Random Number Generation
• Really pseudo-random numbers
• 1. Seed the random number generator only once
#include <cstdlib>
#include <ctime>

srand(time(0));

• 2. The rand() function returns a random integer that is


greater than or equal to 0 and less than RAND_MAX
rand();
Random Numbers
• Use % and + to scale to the number range you want

• For example, to get a random number from 1-6 to


simulate rolling a six-sided die:

int die = (rand() % 6) + 1;

• Can you simulate rolling two dice?

• Generating a random number x where 10 < x < 21?


Type Casting
• Recall the problem with integer division:
int total_candy = 9, number_of_people = 4;
double candy_per_person;
candy_per_person = total_candy / number_of_people;
9/4
• candy_per_person = 2, not 2.25!

• A Type Cast produces a value of one type from another


type
• static_cast<double>(total_candy) produces a double
representing the integer value of total_candy
Type Cast Example
• int total_candy = 9, number_of_people = 4;
double candy_per_person;
candy_per_person = static_cast<double>(total_candy)/ number_of_people;

• candy_per_person now is 2.25!

This would also work:


candy_per_person = total_candy / static_cast<double>(number_of_people);

This would NOT!


candy_per_person = static_cast<double>(total_candy / number_of_people);

Integer division occurs before type cast


Old Style Type Cast
• C++ is an evolving language

• This older method of type casting may be discontinued in


future versions of C++

candy_per_person = double(total_candy)/number_of_people;
Function Declaration
• 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
}
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, double price);
// Compute total cost including 5% sales tax on
// number items at cost of price each
Function Definition
• Provides the same information as the declaration

• Describes how the function does its task

• Example: function header

double total_cost(int number, double price)


{
const double TAX_RATE = 0.05; //5% tax
double subtotal;
subtotal = price * number;
return (subtotal + subtotal * TAX_RATE);
}

function body
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;
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);
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
22
Alternate Declarations
• Two forms for function declarations
• List formal parameter names
• List types of formal parameters, but not names

• Examples:

double total_cost(int number_par, double price_par);

double total_cost(int, double);


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:

// In Function declaration
char grade(int received_par, int min_score_par);
_____________________________________________________

// In Function Called
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!
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 (if any) might have its own return
statement
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.
bool Return Values
• A function can return a bool value
• Such a function can be used where a Boolean
expression is expected
• Makes programs easier to read

if (((rate >=10) && ( rate < 20)) || (rate == 0))

is easier to read as

if (appropriate (rate))

• If the function appropriate returns a bool value based on


the expression above
Function appropriate
• To use the function appropriate in the if-statement
if (appropriate (rate))
{

}

appropriate could be defined as


bool appropriate(int rate)
{
return (((rate >=10) && ( rate < 20)) || (rate == 0));
}
Example: Factorial
• n! Represents the factorial function

• n! = 1 x 2 x 3 x … x n

• The C++ version of the factorial function found in next


slide
• 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
33
Knowledge Check
• Can you

• Determine the value of d?

double d = 11 / 2;

• Determine the value of


pow(2,3) fabs(-3.5) sqrt(pow(3,2))
7 / abs(-2) ceil(5.8) floor(5.8)

• Convert the following to C++

 b  b2  4ac y 7
x y 2a
x
Knowledge Check
• Can you

• Write a function declaration and a function definition for a function


that takes three arguments, all of type int, and that returns the
sum of its three arguments?

• Write a function declaration and a function definition for a function


that takes one argument of type int and one argument of type
double, and that returns a value of type double that is the
average of the two arguments?
36

5.2
Local Variables
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
38
39
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()
{...}

double volume(double number)


{...}

• PI is available to the main() and volume() functions


41
42
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
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
• Example:
int calculate total(int quantity, double price){
……
Formal parameters – local
} scope in the function

• 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
45
46
Block Scope
• Local and global variables conform to the rules of Block
Scope
• The code block (generally defined by the { }) where an identifier
like a variable is declared determines the scope of the identifier
• Blocks can be nested
48
49

5.3
Overloading Function Names
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
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);


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


53
Overloading Example
• The Pizza Buying program
• Rectangular pizzas are now offered!
• Change the input and add a function to compute the unit price of a
rectangular pizza
• The new function could be named unitprice_rectangular
• Or, the new function could be a new (overloaded) version of the
unitprice function that is already used
• Example:

double unitprice(int length, int width, double
price)
{
double area = length * width;
return (price / area);
}
55
56
57
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)
Type Conversion Problem
• Given the previous mpg definition and the following definition in the
same program
// returns the Measure of Perfect Goals
int mpg(int goals, int misses)
{
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 the parameter


types so the Measure of Perfect Goals will be calculated

Do not use the same function name for unrelated functions


60

5.4
void Functions
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
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)


{
cout << f_degrees << “ degrees Fahrenheit is equivalent to
” << c_degrees << “ degrees Celsius.” << endl;
}
63
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);


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
• Example:
void displayMenu(); // function declaration

displayMenu(); // function call with no arguments

• Statements in the 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
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?


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?

• void-function in the next slide, avoids division by zero with a return


statement
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
Knowledge Check
• Can you

• Describe the differences between void-functions and functions that


return one value?

• Tell what happens if you forget the return statement in a void-


function?
73

5.5
Passing Variables in Functions
Call-by-Reference Parameters
• Call-by-value is not adequate when we need a sub-task to obtain input
values

• Call-by-value means that the formal parameters receive the values


of the arguments

• To obtain input values, we need to change the variables that are


arguments to the function

• Recall that we have changed the values of formal parameters in a function body,
but we have not changed the arguments found in the function call

• Call-by-reference parameters allow us to change the variable used in


the function call

• Arguments for call-by-reference parameters must be variables, not


numbers
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!
76
77
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
Call Comparisons
Call By Reference vs Value
• Call-by-reference • Call-by-value
• The function call: • The function call
f(age); f(age);
Memory
Name Location Contents

age 1001 34
initial 1002 A
hours 1003 23.5
1004

void f(int var_par);


void f(int& ref_par);
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
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
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
83
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!
85
Knowledge Check
• Can you

• Write a void-function definition for a function called zero_both that


has two reference parameters, both of which are variables of type
int, and sets the values of both variables to 0.

• Write a function that returns a value and has a call-by-reference


parameter?

• Write a function with both call-by-value and call-by-reference


parameters.
87

LECTURE 6
Functions (Cont.)
Overview
6.1 Functions Calling Functions
6.2 Testing and Debugging
6.3 Arrays in Functions
89

6.1
Functions Calling Functions
Using Procedural Abstraction
• Functions should be designed so they can be used as
black boxes

• To use a function, the declaration and comment should be


sufficient

• Programmer should not need to know the details of the


function to use it
Functions Calling Functions
• A function body may contain a call to another function
• The called function declaration must still appear before it
is called
• Functions cannot be defined in the body of another function

• Example: void order(int& n1, int& n2)


{
if (n1 > n2){
swap_values(n1, n2);
}
}

• swap_values called if n1 and n2 are not in ascending order


• After the call to order, n1 and n2 are in ascending order
92
93
Pre and Postconditions
• Precondition
• States what is assumed to be true before the function
is called
• Function should not be used unless the precondition holds

• Postcondition
• Describes the effect of the function call
• Tells what will be true after the function is executed
(when the precondition holds)
• If the function returns a value, that value is described
• Changes to call-by-reference parameters are described
swap_values revisited
• Using preconditions and postconditions the declaration of
swap_values becomes:

void swap_values(int& n1, int& n2);


//Precondition: variable1 and variable 2 have
// been given values
// Postcondition: The values of variable1 and
// variable2 have been
// interchanged
Function celsius
• Preconditions and postconditions make the declaration for
celsius:

double celsius(double farenheit);


//Precondition: Fahrenheit is a temperature
// expressed in degrees Fahrenheit
//Postcondition: Returns the equivalent temperature
// expressed in degrees Celsius
Why use preconditions
and postconditions?
• Preconditions and postconditions
• should be the first step in designing a function

• specify what a function should do


• Always specify what a function should do before designing how the
function will do it

• Minimize design errors

• Minimize time wasted writing code that doesn’t match the task at
hand
Case Study
Supermarket Pricing
• Problem definition
• Determine the retail price of an item given suitable input
• 5% markup if an item should sell in a week
• 10% markup if an item is expected to take more than a
week
• Summary: 5% for up to 7 days, changes to 10% at 8 days

• Input
• The wholesale price and the estimate of days until the item sells

• Output
• The retail price of the item
Supermarket Pricing:
Problem Analysis
• Three main subtasks
• Input the data
• Compute the retail price of the item
• Output the results

• Each task can be implemented with a function


• Notice the use of call-by-value and call-by-reference parameters in
the following function declarations
Supermarket Pricing:
Function get_input
void get_input(double& cost, int& turnover);

//Precondition: User is ready to enter values


// correctly.
//Postcondition: The value of cost has been set to
// the wholesale cost of one item.
// The value of turnover has been
// set to the expected number of
// days until the item is sold.
Supermarket Pricing:
Function price
double price(double cost, int turnover);

//Precondition: cost is the wholesale cost of one


// item. turnover is the expected
// number of days until the item is
// sold.
//Postcondition: returns the retail price of the item
Supermarket Pricing:
Function give_output
void give_output(double cost, int turnover, double price);

//Precondition: cost is the wholesale cost of one item;


// turnover is the expected time until sale
// of the item; price is the retail price of
// the item.
//Postcondition: The values of cost, turnover, and price
// been written to the screen.
Supermarket Pricing:
The main function
• With the functions declared, we can write the main
function:

int main()
{
double wholesale_cost, retail_price;
int shelf_time;

get_input(wholesale_cost, shelf_time);

retail_price = price(wholesale_cost, shelf_time);

give_output(wholesale_cost, shelf_time, retail_price);

return 0;
}
Supermarket Pricing:
Algorithm Design -- price
• Implementations of get_input and give_output are
straightforward, so we concentrate on the price function

• pseudocode for the price function


• If turnover <= 7 days then
return (cost + 5% of cost);
else
return (cost + 10% of cost);
Supermarket Pricing:
Constants for The price Function
• The numeric values in the pseudocode will be
represented by constants

const double LOW_MARKUP = 0.05; // 5%


const double HIGH_MARKUP = 0.10; // 10%
const int THRESHOLD = 7; // At 8 days use HIGH_MARKUP
Supermarket Pricing:
Coding The price Function
• The body of the price function
{
if (turnover <= THRESHOLD)
return ( cost + (LOW_MARKUP * cost) ) ;
else
return ( cost + ( HIGH_MARKUP * cost) ) ;
}

• See the complete program in next slide


Slide 7-
107
108
109
Supermarket Pricing :
Program Testing
• Testing strategies
• Use data that tests both the high and low markup cases

• Test boundary conditions, where the program is


expected to change behavior or make a choice
• In function price, 7 days is a boundary condition
• Test for exactly 7 days as well as one day more and one day
less
Knowledge Check
• Can you

• Define a function in the body of another function?

• Call one function from the body of another function?

• Give preconditions and postconditions for the predefined function


sqrt?
112

6.2
Testing and Debugging
Testing and Debugging Functions
• Each function should be tested as a separate unit

• Testing individual functions facilitates finding mistakes

• Driver programs allow testing of individual functions

• Once a function is tested, it can be used in the driver


program to test other functions

• Function get_input is tested in the driver program


shown in the next slides
114
115
Stubs
• When a function being tested calls other functions that are
not yet tested, use a stub

• A stub is a simplified version of a function


• Stubs usually provide values for testing rather than
perform the intended calculation

• Stubs should be so simple that you have confidence


they will perform correctly

• Function price is used as a stub to test the rest of the


supermarket pricing program in the next slides
117
118
Rule for Testing Functions
• Fundamental Rule for Testing Functions
• Test every function in a program in which every other function in
that program has already been fully tested and debugged.
Knowledge Check
• Can you

• Describe the fundamental rule for testing functions?

• Describe a driver program?

• Write a driver program to test a function?

• Describe and use a stub?

• Write a stub?
121

6.3
Arrays in Functions
Arrays in Functions
• Indexed variables can be arguments to functions

• Example: If a program contains these declarations:


int i, n, a[10];
void my_function(int n);

• Variables a[0] through a[9] are of type int, making these calls
legal:
my_function( a[0] );
my_function( a[3] ); It passes one single
integer to the function
my_function( a[i] ); as an argument.
NOT THE ARRAY!
123
Arrays as Function Arguments
• A formal parameter can be for an entire array
• Such a parameter is called an array parameter
• It is not a call-by-value parameter
• It is not a call-by-reference parameter
• Array parameters behave much like call-by-reference parameters
Array Parameter Declaration
• An array parameter is indicated using empty brackets in
the parameter list such as

void fill_up(int a[], int size);


Function Calls With Arrays
• If function fill_up is declared in this way:
// function declaration
void fill_up(int a[], int size);

• and array score is declared this way:


// variable and array declaration
int score[5], number_of_scores;

• fill_up is called in this way:


// function call
fill_up(score, number_of_scores);
127
Function Call Details
• A formal parameter is identified as an array parameter by
the []'s with no index expression
// function declaration
void fill_up(int a[ ], int size);

• An array argument does not use the [ ]’s


// function called
fill_up(score, number_of_scores);
Array Formal Parameters
• An array formal parameter is a placeholder for the
argument
• When an array is an argument in a function call, an action
performed on the array parameter is performed on the array
argument

• The values of the indexed variables can be changed by the


function
Array Argument Details
• What does the computer know about an array?
• The base type
• The address of the first indexed variable
• The number of indexed variables

• What does a function know about an array argument?


• The base type
• The address of the first indexed variable
Array Parameter Considerations
• Because a function does not know the size of an array
argument…
• The programmer should include a formal parameter that specifies
the size of the array

• The function can process arrays of various sizes


• Function fill_up can be used to fill an array of any size:

fill_up(score, 5);
fill_up(time, 10);
132
const Modifier
• Array parameters allow a function to change the values
stored in the array argument

• If a function should not change the values of the array


argument, use the modifier const

• An array parameter modified with const is a constant


array parameter
• Example:
void show_the_world(const int a[], int size);
Using const With Arrays
• If const is used to modify an array parameter:

• const is used in both the function declaration and definition to


modify the array parameter

• The compiler will issue an error if you write code that changes the
values stored in the array parameter
Error Message from compiler:
Function Calls and const
• If a function with a constant array parameter calls another
function using the const array parameter as an
argument…

• The called function must use a constant array parameter as a


placeholder for the array

• The compiler will issue an error if a function is called that does not
have a const array parameter to accept the array argument
const Parameters Example
// function declaration
double compute_average(int a[], int size);

void show_difference(const int a[], int size)


{
double average = compute_average(a, size);

}
The array a has no constant

• compute_average has no constant array parameter

• This code generates an error message because


compute_average could change the array parameter
Returning An Array
• Recall that functions can return a value of type int,
double, char, …, or a class type

• Functions CANNOT return arrays


139

C++ Fundamentals -- End

Slides adapted from


Walter Savitch,
“Problem solving with
C++”

You might also like