Upload
lorraine-lachica
View
226
Download
0
Embed Size (px)
Citation preview
8/14/2019 a Function is a Block Of
1/31
1
FUNCTIONS
8/14/2019 a Function is a Block Of
2/31
2
Functions
A function is a block of instructions that isexecuted when it is called from some otherpoint of the program.
Advantages
Reusability
Data Abstraction
Modularity
8/14/2019 a Function is a Block Of
3/31
3
C++ comes with libraries of predefinedfunctions.
How do we use predefined (or library)functions?
Everything must be declared before it is used.The statement #include brings thedeclarations of library functions into yourprogram, so you can use the library functions.
Predefined FunctionsLibraries
8/14/2019 a Function is a Block Of
4/31
Predefined FunctionsLibraries
#include // include declarations of math
// library functions
#include // include definitions of// stdio.h objects
int main()
{
printf( %d\n, sqrt(3.0)) // call math library function
} // sqrt with argument 3.0, send
// the returned value to cout
4
8/14/2019 a Function is a Block Of
5/31
5
Function call
A function call is an expression consisting of a functionname followed by arguments enclosed in parentheses.Multiple arguments are separated by commas.
Syntax:FunctionName(Arg_List)
where Arg_List is a comma separated list of arguments.
Examples:
side = sqrt(area);
printf(2.5 to the power 3.0 is %d, pow(2.5, 3.0));
8/14/2019 a Function is a Block Of
6/31
6
A Function call
//Computes the size of a dog house that can be purchased//given the users budget.#include #include int main( ){
const double COST_PER_SQ_FT = 10.50;double budget, area, length_side;
printf( "Enter the amount budgeted for your dog house $);scanf( %f, &budget);
area = budget/COST_PER_SQ_FT;length_side = sqrt(area); // the function call
8/14/2019 a Function is a Block Of
7/31
7
A Function call
printf( "For a price of $ %d \n" , budget);printf( "I can build you a luxurious square dog house\n);printf("that is %d " ,length_side);printf(" feet on each side.\n);
return 0;}
8/14/2019 a Function is a Block Of
8/31
8
Programmer Defined Functionsfunction prototypes
A function prototype tells you all the information you need tocall the function. A prototype of a function (or its definition)must appear in your code prior to any call to the function.
Syntax: Dontforget the semicolon
Type_of_returned_value Function_Name(Parameter_list); Place prototype comment here.
Parameter_list is a comma separated list of parameterdefinitions:
type_1 param_1, type_2 param_2, . type_N param_N
Example:
double total_weight(int number, double weight_of_one);
// Returns total weight ofnumberof items that
// each weigh weight_of_one
8/14/2019 a Function is a Block Of
9/31
9
Programmer Defined Functions
#include
double total_cost(int number_par, double price_par);
//Computes the total cost, including 5% sales tax,
//on number_par items at a cost of price_par each.
int main( )
{
double price, bill;
int number;
printf( "Enter the number of items purchased: );
scanf( %d, &number);
printf( "Enter the price per item $);
scanf(%d, &price);
bill = total_cost(number, price); The function call
printf(%d items at$ %d each.\n, number, price);
printf( "Final bill, including tax, is $%d\n, bill);
return 0;
8/14/2019 a Function is a Block Of
10/31
10
3.3 Programmer Defined FunctionsDisplay 3.3 A function Definition (Slide 2 of 2)
double total_cost(int number_par, double price_par) The function
{ headingheading
const double TAX_RATE = 0.05; //5% sales tax The function
double subtotal; The function definition
bodysubtotal = price_par * number_par;
return (subtotal + subtotal*TAX_RATE);
}
8/14/2019 a Function is a Block Of
11/31
11
Programmer Defined FunctionsCall-by-value Parameters
Consider the function call:
bill = total_cost(number, price);
The values of the arguments number and price are plugged in
for the formal parameters . This process is (A precise definitionof what plugged means will be presented later. For now, wewill use this simile.)
A function of the kind discussed in this chapter does not sendany output to the screen, but does send a kind of output back
to the program. The function returns a return-statement insteadof cout-statement for output.
8/14/2019 a Function is a Block Of
12/31
12
Programmer Defined FunctionsAlternate form for Function Prototypes
The parameter names are not required:
double total_cost(int number, double price);
It is permissible to write:
double total_cost(int, double );
Nevertheless, code should be readable to programmers as wellas understandable by the compiler, so check for readability andchose to use parameter names when it increases readability.
8/14/2019 a Function is a Block Of
13/31
13
PITFALLArguments in the wrong order
When a function is called, C++ substitutes the first argumentgiven in the call for the first parameter in the definition, thesecond argument for the second parameter, and so on.
There is no check for reasonableness. The only things checked
are: i) that there is agreement of argument type with parametertype and ii) that the number of arguments agrees with the
number of parameters.
If you do not put correct arguments in call in the correct order,C++ will happily assign the wrong arguments to the rightparameters.
8/14/2019 a Function is a Block Of
14/31
14
Programmer Defined FunctionsSummary of Syntax for a Function that Returns a Value.
Function Prototype:
Type_Returned Function_Name(Parameter_List);
Prototype Comment function header
Function DefinitionsType_Returned Function_Name(Parameter_List)
{Declaration_1Declaration_2
. . . Must include one or
Declaration_Last; more return statements.
body Executable_1;Executable_2;. . .
Executable_Last
}
8/14/2019 a Function is a Block Of
15/31
Functions with no return value
8/14/2019 a Function is a Block Of
16/31
General format
void function_name ([parameters])
{
}
8/14/2019 a Function is a Block Of
17/31
Declaring Void Functions
Similar to functions returning a value
Return type specified as "void"
Example: Function declaration/prototype:
void showResults( double fDegrees,double cDegrees);
Return-type is "void"
Nothing is returned
8/14/2019 a Function is a Block Of
18/31
Declaring Void Functions
Function definition:void showResults(double fDegrees,double cDegrees)
{statements;
statements;
} Notice: no return statement
8/14/2019 a Function is a Block Of
19/31
Calling Void Functions
Same as calling predefined void functions
From some other function, like main(): showResults(degreesF, degreesC);
showResults(32.5, 0.3); Notice no assignment, since no
value returned
Actual arguments (degreesF, degreesC)
Passed to function Function is called to "do its job" with the
data passed in
8/14/2019 a Function is a Block Of
20/31
20
Returning more than one value
#include
void prevnext (int x, int &prev, int &next)
{ prev = x-1;
next = x + 1;}
int main {int x = 100,y,z;
prevnext(x,y,z);
printf(previous %d next %d,y, z);
return 0;}
8/14/2019 a Function is a Block Of
21/31
21
Default Values in arguments
#include
int divide(int a, int b=2) {
int r; r=a/b; return(r);}int main(){
printf(%d\n,divide(2));
printf((%d\n, divide(20,4));return 0; }
8/14/2019 a Function is a Block Of
22/31
22
Overloading Function Names
C++ distinguishes two functions by examining thefunction name and the argument list fornumberandtype of arguments.
The function that is chosen is the function with thesame number of parameters as the number ofarguments and and that matches the types of theparameter list sufficiently well.
This means you do not have to generate names forfunctions that have very much the same task, buthave different types.
8/14/2019 a Function is a Block Of
23/31
23
Overloading Function Names
//Illustrates overloading the function name ave.#include
double ave(double n1, double n2);//Returns the average of the two numbers n1 and n2.
double ave(double n1, double n2, double n3);//Returns the average of the three numbers n1, n2, and n3.
int main( ){
using namespace std;
printf( "The average of 2.0, 2.5, and 3.0 is %f \n, ave(2.0, 2.5,3.0));
printf( "The average of 4.5 and 5.5 is %f\n, ave(4.5, 5.5));
return 0;
}
8/14/2019 a Function is a Block Of
24/31
24
Overloading Function Names
double ave(double n1, double n2) Both these functions have the{ same name, but have parameter
return ((n1 + n2)/2.0); lists that are have different} numbers of parameters.
double ave(double n1, double n2, double n3){
return ((n1 + n2 + n3)/3.0);}
8/14/2019 a Function is a Block Of
25/31
25
Overloading Function NamesAutomatic Type Conversion
We pointed out that when overloading function names, the C++compiler compares the number and sequence of types of thearguments to the number and sequence of types for candidatefunctions.
In choosing which of several candidates for use when overloadingfunction names, the compiler will choose an exactmatch if one ifavailable.
An integral type will bepromotedto a larger integral type ifnecessary to find a match. An integral type will be promoted to a
floating point type if necessary to get a match.
8/14/2019 a Function is a Block Of
26/31
8/14/2019 a Function is a Block Of
27/31
8/14/2019 a Function is a Block Of
28/31
28
Overloading Function Names
printf( "Round pizza: Diameter = %d inches\n, diameter);printf( "Price = $ %d" ,price_round);printf( " Per square inch = $%f \n, price_round);printf( "Rectangular pizza: length = %d inches\n" , length );
printf( "Rectangular pizza: Width = %d inches\n" , widht );printf( "Price = $ %d, price_rectangular);printf( " Per square inch = $ %d \n" ,unitprice_rectangular);
if (unit_price_round < unitprice_rectangular)printf( "The round one is the better buy.\n);
elseprintf( "The rectangular one is the better buy.\n);
printf( "Buon Appetito!\n);
return 0;}
8/14/2019 a Function is a Block Of
29/31
29
Function Template
Is a single, complete function that serves asa model for a family of functions
Generic, flexible
Data type of the arguments of the functionfollow the data type of the actual value thatis passed unto it.
8/14/2019 a Function is a Block Of
30/31
30
Function Template
#include template
void showabs(T number){if (number
8/14/2019 a Function is a Block Of
31/31
Reference
Slides by David B Teague, WesternCarolina University,