1 functions chapter 7 2 hope you can function! what is r2d2 doing here? what is his function? who is...

47
1 Functions Functions Chapter 7

Upload: mercy-griffith

Post on 03-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

1

FunctionsFunctionsChapter 7

Page 2: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

2

Hope Hope youyou can function! can function!

What is R2D2 doing here?

What is his function?

Who is Nibble?

Can he function?

IS he a function?

Who is this nut?

Page 3: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

3Top-Down Structured DesignTop-Down Structured Designwith Void Functionswith Void Functions Recall two types of functions Value returning function

– computes a single value– returns value to calling code– uses return command

Void function (procedure)– called as a statement– executes some task

This chapter focuses on the void function

Page 4: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

4

When to Use FunctionsWhen to Use Functions

To help make the program more understandable

To modularize the tasks of the program– building blocks of the program

Write a module once– those lines of source code are called multiple

times in the program

Page 5: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

5

Need for FunctionsNeed for Functions

Functions perform a task.Functions perform a task.

Page 6: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

6

Writing Void FunctionsWriting Void Functions

Declare functions (their names and parameters)– list before main( )– called prototypes

void print_summary (float total);void calculate_rates ( );void find_matching_records (char id[]);

void main ( ) { . . .

void print_summary (float total);void calculate_rates ( );void find_matching_records (char id[]);

void main ( ) { . . .

Function Name Parameter list

Note, must includesemicolon ;

Note, must includesemicolon ;

Page 7: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

7

Writing Void FunctionsWriting Void Functions

Define functions below main( )– specify source code– include heading again

void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }

void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }

Note no semicolon with

definition

Note no semicolon with

definition

Page 8: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

8

Flow of ControlFlow of Control

First statement executed in any program is the first statement in the function main( )

When another function called– logical control passed to first statement in that

function’s body– program proceeds through sequence of statements

within the function When last statement of function executed

– control returns to where function was called– control given to next command after the call

Page 9: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

9

Flow of ControlFlow of Control

void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . } void print_summary (int total) { . . . cout << . . . }

void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . } void print_summary (int total) { . . . cout << . . . }

- first statement of main- function call, jumps to first statement of that function- proceeds through function- returns to next statement after call

- first statement of main- function call, jumps to first statement of that function- proceeds through function- returns to next statement after call

Page 10: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

10

Improving FunctionsImproving Functions

We need to communicate to the functions

We need to communicate to the functions

Page 11: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

11

Improving FunctionsImproving Functions

Sending values to the functionswith value parameters.

Sending values to the functionswith value parameters.

Page 12: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

12

Function ParametersFunction Parameters

Make functions more versatile Send to the function a value

– tells it how many times to do something– gives it a value to be used in some way (printed,

calculated, etc.)

Page 13: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

13

Function ParametersFunction Parameters Formal parameter

– declared in the function heading Actual parameter

– variable or expression listed in a call (invocation) of the function

void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }

void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }

Page 14: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

14

Function Call (Invocation)Function Call (Invocation)

Use the name of the function as if it is a statement

When the program reaches t hat statement, Control is then transferred to the function

void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }

void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }

Page 15: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

15

Function DeclarationsFunction Declarations

Why the prototypes? All identifiers (including function names)

must be declared before they are used

Compiler must know about the function

void calculate_rates ( );void find_matching_records (char id[]);

void main ( ) { . . . calculate_rates ( ); find_matching_records (emp_id);

void calculate_rates ( );void find_matching_records (char id[]);

void main ( ) { . . . calculate_rates ( ); find_matching_records (emp_id);

ParametersParameters

Function nameFunction nameFunction typeFunction type

Page 16: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

16

Function DeclarationsFunction Declarations

It is also legal to include the definition (body) of the function with the heading all before main( )

void print_summary (int total) { . . . cout << . . . } void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . }

void print_summary (int total) { . . . cout << . . . } void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . }

This takes care of informing thecompiler of what it needs

and defining the source code also

This takes care of informing thecompiler of what it needs

and defining the source code also

Page 17: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

17

Syntax of the Parameter ListSyntax of the Parameter List

In parentheses For each parameter

– specify type then name– separate type-name pairs with commas

void print_max_value (int value_1, int value_2, int value_3) { . . . }

void print_max_value (int value_1, int value_2, int value_3) { . . . }

Page 18: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

18

Local VariablesLocal Variables

A variable declared within a block It is not accessible outside of that block Memory allocated when statement reached

within the block Memory de-allocated when block finished

void print_max_value (int value_1, int value_2, int value_3) { int hold_value; hold_value = value_1; if (value_2 > hold_value)

hold_value = value_2; . . . }

void print_max_value (int value_1, int value_2, int value_3) { int hold_value; hold_value = value_1; if (value_2 > hold_value)

hold_value = value_2; . . . }

Block

Page 19: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

19

Local VariablesLocal Variables What if local variable (in the block) has same

name as a variable outside the block? Inside the block

– the local variable takes precedence

– the exterior variable not accessible

Outside the block– the local variable

is not accessible

void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; }

void main( ){ float sum, x, y; . . . print_sum (x, 34); . . .

void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; }

void main( ){ float sum, x, y; . . . print_sum (x, 34); . . .

Page 20: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

20

The Return StatementThe Return Statement A void function does not return a function

value Two ways to have the function return

control to calling routine– when the function finishes all statements– place the command return in the function

void print_odd_even (int x){

if (x % 2) // no remainder => even { cout << "even";

return; }cout << "odd";

}

void print_odd_even (int x){

if (x % 2) // no remainder => even { cout << "even";

return; }cout << "odd";

}

Page 21: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

21

Naming Void FunctionsNaming Void Functions

Remember … void functions are used as statements

The name should suggest what task it is performing– implies use of a verb

It helps the program self document

void print_the_sum ( );void max_value (int a, int b, int c);void calculate_deductions (float hours);void cube_root (float num);

void print_the_sum ( );void max_value (int a, int b, int c);void calculate_deductions (float hours);void cube_root (float num); Which are

good names?Which are

good names?

Page 22: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

22

Header FilesHeader Files

Recall our use of #include <xxxx.h> Header files contain ... named constants like

const int INT_MAX = 32767; new type definitions (besides int, char, etc.) function prototypes like

float pow( float, float );float sqrt( float );char toupper( char );

int islower( char );

Page 23: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

23

Header FilesHeader Files

Note the help window from Turbo C++ concerning header files

We most often use

string.hiostream.hfstream.hiomanip.hmath.h

We most often use

string.hiostream.hfstream.hiomanip.hmath.h

Page 24: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

24

Value ParametersValue Parameters

Defn => a formal parameter that receives a copy of the contents of the corresponding actual parameter

void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }

void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }

17

Page 25: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

25

Value ParameterValue Parameter

Acts much like an assignment of a value to a variable

The formal parameter is considered local to the function

The actual parameter may be an expression or a constant

void main ( ) { print_summary (0.5*rpt_total); . . . print_summary (200); } void print_summary (int total) { . . . cout << . . . }

void main ( ) { print_summary (0.5*rpt_total); . . . print_summary (200); } void print_summary (int total) { . . . cout << . . . }

Page 26: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

26

Value ParametersValue Parameters

Consider … When we change the contents of the value parameter in the function …– What (if anything) happens to the actual

parameter?

No, nothing happens.The actual parameter remains unchanged

No, nothing happens.The actual parameter remains unchanged

Page 27: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

27

Reference ParametersReference Parameters

What if we wanted the actual parameter to change?

C++ allows us to do this with reference parameters.

What is different in thisversion of the function?What is different in thisversion of the function?

Page 28: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

28

Reference ParametersReference Parameters

It would be helpful tobe able to have the functions

communicate back to thecalling module.

It would be helpful tobe able to have the functions

communicate back to thecalling module.

Page 29: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

29

Reference ParametersReference Parameters

Reference Parameters providethat capability

Reference Parameters providethat capability

Page 30: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

30

Reference ParametersReference Parameters

Use the ampersand & between the parameter type and the identifier

What actually happens is that this causes the address of the actual parameter to be sent to the formal parameter

Then anything that happens to the formal parameter is happening to the actual parameter

Page 31: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

31Contrast Contrast Value & Reference ParametersValue & Reference Parameters

Receives copy of value Actual parameter can be

constant, variable, expression

Value travels one way only (in)

Exact match of types (formal & actual) not critical

Receives address of actual parameter

Actual parameter must be a variable

Value can be thought of as traveling both ways (in and out)

Formal & actual parameters must be of same type

ValueValue ReferenceReference

Page 32: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

32

Reference ParametersReference Parameters

5 10

5

Recall our previous model for a function with value parameters(values go in only)

Now consider a new version for reference parametersValues go bothin & out

Page 33: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

33

Another Look at Value Another Look at Value ParametersParameters

CALLINGBLOCK

FUNCTION CALLED

“incoming”

value ofactual parameter

Sometimes called“Pass-by-value”

Page 34: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

34

Another Look at Reference Another Look at Reference ParametersParameters

CALLINGBLOCK FUNCTION

CALLED

“incoming”

original value ofactual parameter

“outgoing”

changed value ofactual parameter OR,Sometimes called

“Pass by reference”Sometimes called

“Pass by reference”

Page 35: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

35

Another Version ofAnother Version ofPass-by-referencePass-by-reference

CALLINGBLOCK FUNCTION

CALLED

actual parameter has no value yet when call occurs

“outgoing”

new value ofactual parameter

Page 36: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

36Matching Actual & Formal Matching Actual & Formal ParametersParameters Must be same number of parameters in call

as in declaration/definition Parameters are paired off left to right as they

occur void print_max (int n1, int n2, int n3) { if ( … … cout << … }

int main(){ … print_max (x, 17, y + z); …

void print_max (int n1, int n2, int n3) { if ( … … cout << … }

int main(){ … print_max (x, 17, y + z); …

Page 37: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

37

Actual & Formal ParametersActual & Formal Parameters

Actual (in the call) value parameters may be variables, constants, or expressions

void print_max (int n1, int n2, int n3) { if ( … … cout << … }

int main(){ … print_max (x, 17, y + z); …

void print_max (int n1, int n2, int n3) { if ( … … cout << … }

int main(){ … print_max (x, 17, y + z); …

Page 38: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

38

Actual & Formal ParametersActual & Formal Parameters

Actual (in the call) reference parameters must be variables

void swap (int &n1, int &n2) { int hold = n1; n1 = n2; n2 = hold}

int main(){ int x = 5; y = 3; z = 12 swap (x, z); swap (z, y); …

void swap (int &n1, int &n2) { int hold = n1; n1 = n2; n2 = hold}

int main(){ int x = 5; y = 3; z = 12 swap (x, z); swap (z, y); …

What ends up stored where?

Or … who’s on first?

What ends up stored where?

Or … who’s on first?

x = y = z = x = y = z =

Page 39: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

39

Reusing FunctionsReusing Functions

A programmer can use reuse functions– from other programs you have written– utility functions from other sources

Such functions can be considered “black boxes”– you merely call the function– you need not know how it does what it does– this is called “encapsulation”

Page 40: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

40

Reusing FunctionsReusing Functions

To call a function a programmer must know the interface– the name of the function

– the names and types of the parameters

– any pre- or post-conditions Pre-conditions -- any requirements of the function

– max or min values of parameters

– a certain file must be open, etc. Post-conditions -- guaranteed results if pre-

conditions met

Page 41: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

41

The Assertion StatementThe Assertion Statement A command that declares a certain condition

– if the condition is not met, the program is halted with an error message

Helps programmer catch pre-conditions or other program module requirements

The assertions can also help comment or document the program

Note #include <assert.h>Note #include <assert.h>

Page 42: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

42

Preconditions and PostconditionsPreconditions and Postconditions

The precondition is an assertion describing everything that the function requires to be true at the moment the function is invoked.

The postcondition describes the state at the moment the function finishes executing.

The caller is responsible for ensuring the precondition, and the function code must ensure the postcondition.

FOR EXAMPLE . . .

Page 43: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

43

Function with PostconditionsFunction with Postconditionsvoid GetRating ( /* out */ char& Letter)// Precondition: None// Postcondition:User has been prompted to enter a char// && Letter == one of these input values: E,G,A, or P{ cout << “Enter employee rating.” << endl;

cout << “Use E, G, A, or P : ” ; do { cin >> Letter; if ( (Letter != ‘E’) && (Letter != ‘G’)

&& (Letter != ‘A’) && (Letter != ‘P’) )

cout << “Rating invalid. Enter again: ”; } while ( (Letter != ‘E’) && (Letter != ‘G’)

&& (Letter != ‘A’) && (Letter != ‘P’) );}

void GetRating ( /* out */ char& Letter)// Precondition: None// Postcondition:User has been prompted to enter a char// && Letter == one of these input values: E,G,A, or P{ cout << “Enter employee rating.” << endl;

cout << “Use E, G, A, or P : ” ; do { cin >> Letter; if ( (Letter != ‘E’) && (Letter != ‘G’)

&& (Letter != ‘A’) && (Letter != ‘P’) )

cout << “Rating invalid. Enter again: ”; } while ( (Letter != ‘E’) && (Letter != ‘G’)

&& (Letter != ‘A’) && (Letter != ‘P’) );}

States function’s guaranteeStates function’s guarantee

Page 44: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

44

Function with Preconditions Function with Preconditions and Postconditionsand Postconditions

void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& Root1, /* out */ float& Root2 )

// Precondition: a, b, and c are assigned// && a != 0 && b*b - 4*a*c != 0// Postcondition: Root1 and Root2 are assigned && Root1 and Root2 // are roots of quadratic with coefficients a, b, c{

float temp;

temp = b * b - 4.0 * a * c;

Root1 = (-b + sqrt(temp) ) / ( 2.0 * a );

Root2 = (-b - sqrt(temp) ) / ( 2.0 * a );

return;}

void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& Root1, /* out */ float& Root2 )

// Precondition: a, b, and c are assigned// && a != 0 && b*b - 4*a*c != 0// Postcondition: Root1 and Root2 are assigned && Root1 and Root2 // are roots of quadratic with coefficients a, b, c{

float temp;

temp = b * b - 4.0 * a * c;

Root1 = (-b + sqrt(temp) ) / ( 2.0 * a );

Root2 = (-b - sqrt(temp) ) / ( 2.0 * a );

return;} If preconditions are met,

postconditions areguaranteed

If preconditions are met,postconditions are

guaranteed

Why needed?Why needed?

Page 45: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

45

Documenting Data Flow DirectionDocumenting Data Flow Direction

Data Flow <=> flow of information ...– from the call of the function – into the function– then from the function (if it is a reference

parameter)– back to where it is called

Specify in a comment in the parameter list

void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& Root1, /* out */ float& Root2 )

void GetRoots( /* in */ float a, /* in */ float b, /* in */ float c, /* out */ float& Root1, /* out */ float& Root2 )

Page 46: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

46

Testing and Debugging HintsTesting and Debugging Hints

Note documentation guidelines, Appendix E (pg A10-A13)

Make sure to have function prototypes near top of program

Use semicolon after prototype, but not after definition

Formal parameter list must specify type for each parameter

Use value parameters unless value must be returned to actual parameter

Page 47: 1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is

47

Testing and Debugging HintsTesting and Debugging Hints

Reference parameters must have & with the data type

Match sequence of actual parameter list to formal parameter list

Reference parameters must have variables in the call

Remember to use ... – debugger– variable watch window