cs 117 spring 2002 functions hanly - chapter 5 friedman-koffman - sections 3.1-3.6 & chapter 6
Post on 20-Dec-2015
227 views
TRANSCRIPT
CS 117 Spring 2002
Functions
Hanly - Chapter 5
Friedman-Koffman - Sections 3.1-3.6 & Chapter 6
2/25/02
• Program 3 questions– A heading of 90 could result in bearings of
either N 90 E or S 90 E. Either is OK.
• Exam 2 - Mar 6
• clearInput.cpp
Functions
• mathematical functions express a relationship between variablesy = f(x)
• procedures use information given to them and perform some action
• functions provide a different kind of program flow
Functions we've seen already
• main is a functionint main( void) {...}
• functions from math libraryz = sqrt( x);
Library Functions
math.h common mathematical functions and constants
ctype.h char functions: tolower, isdigit, …
stdlib.h utility functions
string.h char array functions - we'll see this later
user-defined functions
• when libraries don't provide what you need, write your own
• When do you need a function?– something that is done several times in your program
– something that you want to do in different programs
– a long and/or complicated series of operations that make the flow of the program difficult to follow
Function as Black Box
• means of hiding details
• can use them without knowing what is inside (details of how they work)
output = function( input1, input2)
arguments (input1 and input2) provide information to the program
return value carries information back to calling function
Writing a function
• prototype– a template for calling the function
• used by the compiler to verify the function is being called correctly
• shows the user how to call the function
• definition – code that defines what the function does (and
how)– executed when the program runs
function prototype
• The function prototype or declaration has the formreturnType functionName( paramList);
• where:– returnType is the type of the value returned by the
function
– paramList is a comma separated list of zero or more parameter types
function definition
• The function definition has the formreturnType functionName( paramList){/* local variable declarations *//* code that defines what the function does */return someValue;}
• the first line (signature) must match the prototype exactly
• paramList must have types and names of parameters
Example - double to integer power
• prototypedouble power( double, int);
• definitiondouble power( double x, int n) {double ans = 1;for (int j=0; j<n; j++)
ans *= x;return ans;}
Using functions
• use a function by calling it x = sqrt( y);
• function callfunctionName( argList)
• argList is a comma separated list of values – must match the formal parameter list in type and
number of values– values may be any expressions compatible with the
type of the formal parameter– provides information the function needs to do its job
using functions, cont.
• can call a function anywhere that an expression of the type that the function returns can go
• variables passed to a function do NOT have to have the same name as the formal parameter– do you even know the name of the formal parameter for
sqrt?
2/27/02
• Program 3 due Friday• Program 4 on the web
• Exam 2 - Wednesday Mar 6
• office hours Thursday 9:30-10:30
• labs will be unavailable Saturday afternoon
functions
• prototypereturnType fnName( paramList);
• definition returnType fnName( paramList){ // function bodyreturn returnValue;}
• usevar = fnName( argList);
functions with no arguments
• Functions do not have to have any arguments.
• example: rand from math.h– takes no input – returns a random number
• declared with either the keyword void or nothing in the argument list
Argument / Parameter List Correspondence
– Functions can have more than 1 arg– Correspondence between Actual & Formal
arguments
Function call scale (3.0, z);
Actual Argument Formal Argument
3.0 x
z n
return types
• function that needs to return information has a return type appropriate to the information being returned
• return statement is used to pass the information back to the calling function
types and functions
• Type of a value returned by a called function must be consistent with the type expected by the caller as identified in the prototype
• Type of an actual argument in a function call must be consistent with the type of its corresponding formal argument
void functions
• some functions don’t return a value– return type is void
• An example would be a function that prints its arguments out in a particular format.
• use return without any value following it to exit from the function
• function call is an independent statement– doThis( );
Type Conversion in function calls
• When you pass a variable to a function that is a different type than specified in the function declaration, the compiler will attempt to cast the variable to the appropriate type.
• This works for most pre-defined types but may not give what you expect. – Doubles will be truncated on conversion to an int.
Scope
• There are limits to where a variable is visible
3.6 Scope of Names
• Variable declared in a function has a local scope within the function
• Same for variables declared in the main
• Variable declared before main is global scope– Call anywhere in program
• Functions declared globally
Scope of Names
• Positional correspondence
• Type consistent is key because of positional correspondence– Argument types– Return types
Variable Scope
• Local Variables– Variables declared inside a function body are local to that
function. – They cannot be seen outside the function. – The parameters of the function are also local variables
• Global variables– Variables that are declared outside of any function
(including main).– They can be seen by all functions in the file in which they
occur. – This is most useful for constants.
Order of Execution
int main()
{
drawCircle();
drawTriangle();
drawIntersect();
return 0;
}
void drawCircle()
{
cout << “ * “ << endl;
cout << “ * * “ << endl;
cout << “ * * “ << endl;
}
Common errors
– Re-declaring parameters inside function– stray code
• the only statements that are allowed outside of function bodies are declarations
– semicolon after signature in function definition
3/1/02
• CS department computer lab not availabe Saturday afternoon
• Program 3
• Program 4
• Exam 2
scope.cppconst int MAX = 100; double x; // global variableint p( double );int k( int );int main() { double m = 14.6; for (int x = 0; x < MAX; ++x) { int z= k( x ); if (z == 0) cout << x << endl; } cout << p(m) << endl; return 0; }
int p( double k ) {
x = k - 0.5;
int i = k * 3;
return i;
}
int k( int m ) {
return (m % 10);
}
Pass by value
• When you call a function, the function gets a value to associate with each parameter.
• A variable or expression passed to a function is evaluated and only the value is passed to the function.
• a variable passed to a function, that variable will not get modified by the function
• Pass by value is the default behavior for function parameters
Pass by reference
• pass the address of a variable instead of its value• the function uses the original variable instead of a
copy • get a reference parameter by putting an & between
the type and the name of a parameter in the function declaration
• reference argument must be a variable• allows functions to return more than one value
Example - the swap function
void swap( double & x, double & y)
{
double temp;
temp = x;
x = y;
y = temp;
}
function overloading
• can define multiple functions with the same name– signatures must be different
• number and/or types of the arguments must differ.
• example : absolute value function– int abs( int n);– long abs( long l);– double abs( double d);
• arithmetic and input/output operators are overloaded for all the standard types
• not all languages allow you to do this
header files
• either a prototype or function definition must appear in the file before the function can be called
• header files may contain prototypes for a group of related functions
• math.h declares all the functions in the math library
• include a header file at the beginning of a program file allows the compiler to recognize the functions when they are called.
user-defined header files
• to include your own header files, use#include "myHeader.h"
• the compiler will look for the file myHeader.h in the same directory as your program
Function Advantages
– Program team on large project
– Simplify tasks
– Each Function is a separate unit
– Top-down approach
– Procedural abstraction
– Information hiding
– Reuse (drawTriangle)
Top-down programming
• Design your programs by breaking them down into smaller parts.
• Do this the way you might organize a paper.
• Start with a broad outline and then fill in more detail at each level until you have something that is complete.
3.1 Building Programs from Existing Information
– Reuse of existing programs
– Develop program in stages
– Compile along the way
– Keep it small
– Comments to describe actions
Figures
/\ / \/ \------| | | | | |------
** * * ** /\ / \/ \------ /\ / \/ \
Top-Down Design and Structure Charts
Draw aCircle
Drawintersecting
lines
Draw abase
Draw aTriangle
Drawintersecting
lines
Draw afigure
Original Problem
Detailed
subproblems
Level 0
Level 1
Level 2
Abstraction
– Abstraction:• Refers to the act of ignoring details to
concentrate on essentials.• Allows us to use complicated things with
little effort (CD players, automobiles, computers).
Programming Style Guidelines
Use comments to specify preconditions and postconditions for functions
Use comments in formal parameter list to explain what they are
Function names should reflect the purpose of the function.
Preconditions & Postconditions
– Comments that represents a contract between the implementor of a function and the user (client) of that function.
– We'll look at two such comments:• Precondition: What the function requires.• Postcondition: What the function will do if
the precondition is met.
Preconditions and Postconditions
– The preconditions are the circumstances that must be true before the function can successfully fulfill the promised postconditions.
– Example (Precondition abbreviates to PRE:
double sqrt(double x);// PRE: x >= 0// POST: Returns square root of argument X
Style Guidelines
• Don't use global variables.
• Don't reuse variable names in different parts of the program
Function Return
• Functions must return a value unless declared as void
Form: return expression;
Example: return x * y;
Common Programming Errors
– Semicolon in Function Prototype (Declaration)– Inconsistencies in Number of Arguments
• Too few arguments in a call
• Too many arguments in a call
• Incorrect number of arguments in call
• Extra argument in call
– Argument Mismatch• Correct position (formal & actual params)
Common Programming Errors
– Function Prototype & Definition Mismatches• Both are the same except for the ;
– Return Statements• “Return value expected”
• “Function should return value”
– Missing #include
Recursive functions
• functions that call themselves
factorial function
• Consider the factorial function:– n! = n * (n-1) * (n-2) * ... *2 * 1
• The prototype or declaration for this function would look likeint factorial (int n);
• To calculate 6! you might call the function as follows:cout << factorial(6);
factorial definition
int factorial (int n) {int product = 1;while (n>1) {
product = product * n;n--;}
return product;}