cs 117 spring 2002 functions hanly - chapter 5 friedman-koffman - sections 3.1-3.6 & chapter 6

51
CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Post on 20-Dec-2015

227 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

CS 117 Spring 2002

Functions

Hanly - Chapter 5

Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Page 2: 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

Page 3: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 4: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Functions we've seen already

• main is a functionint main( void) {...}

• functions from math libraryz = sqrt( x);

Page 5: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 6: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 7: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 8: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 9: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 10: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 11: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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;}

Page 12: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 13: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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?

Page 14: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 15: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

functions

• prototypereturnType fnName( paramList);

• definition returnType fnName( paramList){ // function bodyreturn returnValue;}

• usevar = fnName( argList);

Page 16: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 17: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 18: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 19: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 20: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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( );

Page 21: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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.

Page 22: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Scope

• There are limits to where a variable is visible

Page 23: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 24: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Scope of Names

• Positional correspondence

• Type consistent is key because of positional correspondence– Argument types– Return types

Page 25: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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.

Page 26: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Order of Execution

int main()

{

drawCircle();

drawTriangle();

drawIntersect();

return 0;

}

void drawCircle()

{

cout << “ * “ << endl;

cout << “ * * “ << endl;

cout << “ * * “ << endl;

}

Page 27: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 28: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

3/1/02

• CS department computer lab not availabe Saturday afternoon

• Program 3

• Program 4

• Exam 2

Page 29: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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);

}

Page 30: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 31: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 32: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Example - the swap function

void swap( double & x, double & y)

{

double temp;

temp = x;

x = y;

y = temp;

}

Page 33: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 34: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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.

Page 35: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 36: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Function Advantages

– Program team on large project

– Simplify tasks

– Each Function is a separate unit

– Top-down approach

– Procedural abstraction

– Information hiding

– Reuse (drawTriangle)

Page 37: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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.

Page 38: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 39: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Figures

/\ / \/ \------| | | | | |------

** * * ** /\ / \/ \------ /\ / \/ \

Page 40: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 41: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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).

Page 42: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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.

Page 43: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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.

Page 44: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 45: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Style Guidelines

• Don't use global variables.

• Don't reuse variable names in different parts of the program

Page 46: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Function Return

• Functions must return a value unless declared as void

Form: return expression;

Example: return x * y;

Page 47: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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)

Page 48: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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

Page 49: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

Recursive functions

• functions that call themselves

Page 50: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

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);

Page 51: CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections 3.1-3.6 & Chapter 6

factorial definition

int factorial (int n) {int product = 1;while (n>1) {

product = product * n;n--;}

return product;}