1 functional abstraction function prototypes & api’s formal vs. actual parameters value vs....

24
1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z), lineOf(ch,n), swap(&x,&y) Where to put function declarations How to call Putting It All Together fundemo.cpp CSE 20232 CSE 20232 Lecture 10 – Functions Lecture 10 – Functions

Upload: alycia-bower

Post on 01-Apr-2015

223 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

1

Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions

max(x,y), avg(x,y,z), lineOf(ch,n), swap(&x,&y) Where to put function declarations How to call Putting It All Together

fundemo.cpp

CSE 20232CSE 20232Lecture 10 – FunctionsLecture 10 – Functions

Page 2: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

2

Functional Abstraction

A function performs a specified task, given stated preconditions and postconditions

It has a name, parameters and a return value It may be used “by name” as long as …

appropriate values or objects are passed to it as parameters,

its preconditions are met its return value is used in an appropriate context

In this sense we have “abstracted” the function and “hidden” its implementation details

Page 3: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

3

API – Application Programmer Interface

An API specifies available functions and classes in a way that … hides implementation details gives the software developer enough information about

them to use them properly

An API description of a function would include … Its prototype Its preconditions and postconditions A brief description of what it does, what it returns, and how

it uses its parameters to do so

Page 4: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

4

Function Prototypes

General format of a protoype

<return type> <name> ( <parameter_list> )

Prototypes are used to inform the compiler of the function’s existence

Prototypes appear in .. Header files Near the beginning of code files, before any use

of the function

Page 5: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

5

Functions – A key point!

A function’s existence MUST be declared BEFORE any call to (use of) that function

Failing this, the compiler will complain that the function is NOT defined

Think about it …! You cannot properly use a new word in a written paper until

you know … … how to spell it. … what it means . … what its proper grammatical usage is.

Same thing applies to new functions you create!

Page 6: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

6

API Example – max(x,y)

Prototype double max(double x, double y);

Preconditions None

Postconditions Parameter values are unchanged and function

returns a copy of the larger parameter’s value

Description Function returns a value equal to the

larger parameter x or y

Page 7: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

7

Use of a function A function is called (invoked or used) by placing its name with

appropriate actual parameters in a statement, or as a statement in your C++ code

Note: a function’s return value replaces it in its calling context

Example: use max(x,y) to find largest of 3 values

// make two calls in sequencelarger = max(value1,value2);largest = max(larger,value3);

// or pass return value of first call as // parameter to second calllargest = max( max(value1,value2), value3);

Page 8: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

8

Implementing a Function

Function implementation involves … Writing the code that performs the task described

in the function’s API description The details of this are most likely hidden from the

user of the function The function may be in the same file as main() or

in a separate file Function libraries may even be separately

compiled

Page 9: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

9

Implementing a function General format of a function implementation

<return type> <name> (<parameter_list>) { <local_declarations> <statements> }

Notes: These parameters are the function’s formal parameters.

Names are meaningful only within the function block. The scope of local declarations is only within the function

block.

Page 10: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

10

Implementing max(x,y)

The max(x,y) function is implemented below

double max(double x, double y) { double maxVal = x; if (maxVal < y) maxVal = y; return maxVal; }

Formal parameters (x,y), and local variable (maxVal) only exist inside the function while it is executing

Page 11: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

11

Program example – finding maximum of three values// maxOf3.cpp – JHS 2006// finds maximum value out of three entered#include <iostream>using namespace std;double max(double x, double y); // function prototype

int main(){ double val1,val2,val3; cout << “Enter three real numbers:”; cin >> val1 >> val2 >> val3; cout << “The largest value is: “ << max(max(val1,val2), val3) << endl; return 0;}double max(double x, double y) // function implementation{ double maxVal = x; if (maxVal < y) maxVal = y; return maxVal;}

Page 12: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

12

Program example – alternate arrangement of code// maxOf3.cpp – JHS 2006// finds maximum value out of three entered#include <iostream>using namespace std;

double max(double x, double y) // function implementation{ // also serves as prototype double maxVal = x; if (maxVal < y) maxVal = y; return maxVal;}

int main(){ double val1,val2,val3; cout << “Enter three real numbers:”; cin >> val1 >> val2 >> val3; cout << “The largest value is: “ << max(max(val1,val2), val3) << endl; return 0;}

Page 13: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

13

Parameter Types …

Constant Parameters (const int x) Compiler flags any attempt to change the

parameter value as an error Value Parameters (int x)

Formal parameter is actually a copy of the value of the actual parameter in the function call

Any changes made to the parameter are local in affect, and do not modify the actual parameter value

Page 14: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

14

Parameter Types …

Reference Parameters (int &x) Formal parameters are addresses of or references to the

actual parameters In essence the formal parameter names are aliases for the

actual parameters Any changes made to the formal parameters are changes

made to the actual parameters Default Parameters (int x = 5)

Set value of parameter if no actual parameter appears in the call

All parameters to the right of a parameter having a default value must also have default values

Page 15: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

15

Constant parameter

The cube function returns the cube of the constant parameter x

int cube(const int x)

{

// any attempt to change the value

// of x here would be an error

return(x*x*x);

}

Page 16: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

16

Reference parameters

The swap function swaps the values of its two reference parameters

void swap(int &x, int &y){ int temp = x; // temp only exists while swap runs x = y; y = temp;}

// sample calls from main()swap(a,b); // this call swaps values of a & bswap(val1,val2); // this one swaps values of val1 & val2

Page 17: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

17

Value Parameters The function lineOf outputs a line of n copies of the character ch

to the screen

void lineOf(char ch, int n){ while (n > 0) { cout << ch; n--; // changes only the local copy of the actual parameter }}

// sample calls from main()lineOf(‘+’,20); // this call outputs 20 plus signslineOf(‘.’,num); // this one outputs num periods, num unchanged

Page 18: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

18

Default Parameters

The increment function uses a default value of 1 for the amount it adds to n

void increment(int &n, int amount = 1){ n = n + inc;}

// sample calls from main()increment(a,12); // same as a = a + 12;increment(count); // same as count = count + 1;

Page 19: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

19

Putting it all together// fundemo.cpp – JHS 2006// demonstrates creation and use of functions// reads a file of integer pairs (a & b) and ... // counts the number of pairs// finds averages of all the max(a,b) and min(a,b)// outputs each a & b pair reordered so a <= b // outputs a line |a-b| plus signs on each line// outputs summary of calculations

#include <iostream>#include <fstream>#include <iomanip>using namespace std;

// function prototypesvoid swap(int &x, int &y); void increment(int &n, int amount = 1);int max(const int x, const int y); void lineOf(char ch, int n);

Page 20: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

20

Putting it all togetherint main(){ ifstream infile(“pairs.txt”); int a, b, sumMax(0), sumMin(0), count(0); while(infile >> a >> b) { if (a == max(a,b)) swap(a,b); increment(sumMin,a); increment(sumMax,b); increment(count); cout << setw(5) << a << setw(5) << b << “ “; lineOf(‘+’, b-a); cout << endl; } cout << “Average of mins : “ << sumMin/(float)count << endl; cout << “Average of maxes: “ << sumMax/(float)count << endl; return 0;}

Page 21: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

21

Putting it all together// function implementations

// swap values of parameters a & bvoid swap(int &x, int &y){ int temp = x; x = y; y = temp;}

// return maximum value, either x or yint max(const int x, const int y){ int maxVal = x; if (x < y) maxVal = y; return maxVal;}

Page 22: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

22

Putting it all together// more function implementations

// increment n by amount specified, same as n = n + amountvoid increment(int &n, int amount) // note default value not here{ n = n + amount;}

// show line of n chars same as value of chvoid lineOf(char ch, int n){ while (n > 0) { cout << ch; n--; }}

Page 23: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

23

Sample pairs.txt

12 23

45 39

1 2

4 6

9 4

-5 -3

Page 24: 1 Functional Abstraction Function Prototypes & API’s Formal vs. Actual Parameters Value vs. Reference Parameters Some Simple Functions max(x,y), avg(x,y,z),

24

Sample run of fundemo

12 23 +++++++++++

39 45 ++++++

1 2 +

4 6 ++

4 9 +++++

-5 -3 ++

Average of mins : 9.16667

Average of maxes: 13.6667