41
1 Simple Functions Simple Functions Writing Reuseable Formulas Writing Reuseable Formulas

Simple Functions

  • Upload
    channer

  • View
    89

  • Download
    1

Embed Size (px)

DESCRIPTION

Simple Functions. Writing Reuseable Formulas. In Math. Suppose f (x) = 2 x 2 +5 f(5)=? f(5) = 2*5 2 +5 =55 f(7) = 2*7 2 +5 =103. 135. 165. Problem. - PowerPoint PPT Presentation

Citation preview

Page 1: Simple Functions

1

Simple FunctionsSimple Functions

Writing Reuseable FormulasWriting Reuseable Formulas

Page 2: Simple Functions

In MathIn Math

• Suppose f (x) = 2 xSuppose f (x) = 2 x22+5+5

• f(5)=?f(5)=?

• f(5) = 2*5f(5) = 2*522+5 =55+5 =55

• f(7) = 2*7f(7) = 2*722+5 =103+5 =103

2

Page 3: Simple Functions

3

ProblemProblem

Using OCD, design and implement a program Using OCD, design and implement a program that computes the area and circumference that computes the area and circumference of an Australian Rules Football field, which of an Australian Rules Football field, which is an ellipse that is (ideally) 165m x 135m.is an ellipse that is (ideally) 165m x 135m.

135

165

Page 4: Simple Functions

4

Problem GeneralizationProblem Generalization

Using OCD, design and implement a Using OCD, design and implement a program that computes the area and program that computes the area and circumference of an circumference of an ellipseellipse..

2)

222

( bancecircumfere

abarea a

a

bb

Page 5: Simple Functions

5

BehaviorBehavior

Our program should display on the Our program should display on the screen its purpose and prompt the screen its purpose and prompt the user for the length and width of the user for the length and width of the ellipse. It should then read the length ellipse. It should then read the length and width from the keyboard. It and width from the keyboard. It should then compute and display the should then compute and display the ellipse’s area and circumference, along ellipse’s area and circumference, along with a descriptive label.with a descriptive label.

Page 6: Simple Functions

6

ObjectsObjects

Description Type Kind NameDescription Type Kind Name

purpose string constant --prompt string constant --length double variable lengthwidth double variable width

circumference double variable circumferencearea double variable area

screen ostream varying cout

keyboard istream varying cin

double constant PIa double variable halfLengthb double variable halfWidth

Page 7: Simple Functions

7

OperationsOperations

Description Predefined? Library? NameDescription Predefined? Library? Name

display strings yes iostream <<read doubles yes iostream >>compute circumf. no -- --- multiply doubles yes built-in *

compute area no -- --- multiply doubles yes built-in *display doubles yes iostream <<

- add doubles yes built-in +- divide doubles yes built-in /- exponentiation yes cmath pow()- square root yes cmath sqrt()

Page 8: Simple Functions

8

AlgorithmAlgorithm

0. Display via cout the purpose of the program plus a 0. Display via cout the purpose of the program plus a prompt for the length and width of an ellipse.prompt for the length and width of an ellipse.

1. Read 1. Read lengthlength, , widthwidth from from cincin..

2. Compute 2. Compute halfLengthhalfLength = = lengthlength/2.0; /2.0; halfWidthhalfWidth = = widthwidth/2.0./2.0.

3. Compute 3. Compute areaarea = = PI * halfLength * halfWidthPI * halfLength * halfWidth..

4. Compute 4. Compute circumferencecircumference = 2.0 * PI * = 2.0 * PI * sqrt((sqrt((halfLengthhalfLength22 + + halfWidth halfWidth22)/2.0). )/2.0).

5. Display 5. Display areaarea and and circumferencecircumference with descriptive with descriptive labels.labels.

Page 9: Simple Functions

9

CodingCoding#include <iostream> // cin, cout, <<, >>, ...#include <cmath> // sqrt(), pow(), ...using namespace std;int main(){ const double PI = 3.14159; cout << "\nTo compute the area and circumference" << "\n of an ellipse, enter its length and width: "; double length, width; cin >> length >> width; double halfLength = length/2.0, halfWidth = width/2.0; double area = PI * halfLength * halfWidth; double circumference = 2.0 * PI * sqrt((pow(halfLength, 2.0) + pow(halfWidth,

2.0))/2.0);

cout << "\nThe area is " << area << "\n and the circumference is " << circumference << endl;}

Page 10: Simple Functions

10

TestingTesting

To compute the area and circumference

of an ellipse, enter its length and width: 165 135

The area is 17494.7

and the circumference is 473.589

Page 11: Simple Functions

11

ProblemProblem

We’ve done a fair amount of work in We’ve done a fair amount of work in creating these formulas, but have no creating these formulas, but have no way to directly reuse that work if we way to directly reuse that work if we ever need to use these ellipse-related ever need to use these ellipse-related formulas again...formulas again...

Solution: Rewrite those formulas as Solution: Rewrite those formulas as functionsfunctions..

Page 12: Simple Functions

12

Using Functions (i)Using Functions (i)#include <iostream> // cin, cout, <<, >>, ...#include <cmath> // sqrt(), pow(), ...using namespace std;

double EllipseArea(double length, double width);double EllipseCircumference(double length, double width);

int main(){ cout << "\nTo compute the area and circumference" << "\n of an ellipse, enter its length and width: "; double length, width; cin >> length >> width;

double area = EllipseArea(length, width); double circumference = EllipseCircumference(length,width);

cout << "\nThe area is " << area << "\n and the circumference is " << circumference << endl;}

Page 13: Simple Functions

13

Using Functions (ii)Using Functions (ii)

const PI = 3.14159;

double EllipseArea(double length, double width);{ double halfLength = length/2.0, halfWidth = width/2.0; return PI * halfLength * halfWidth;}

double EllipseCircumference(double length, double width);{ double halfLength = length/2.0, halfWidth = width/2.0; return 2.0 * PI * sqrt((pow(halfLength, 2.0) + pow(halfWidth,

2.0))/2.0);}

Page 14: Simple Functions

14

Simplify for math Simplify for math functionsfunctions

const PI = 3.14159;

double f(double x, double y);{ double a = x/2.0, b = y/2.0; return PI * a * b;}// f(x,y)= (x/2)(y/2)

double g(double x, double y);{ double a = l/2.0, b = w/2.0; return 2.0 * PI * sqrt((pow(a, 2.0) + pow(b, 2.0))/2.0);}//g(x,y) = 2

2/))2/()2/(( 22 yx

Page 15: Simple Functions

15

Function PrototypesFunction Prototypes

A function prototype acts as a A function prototype acts as a declaration of the function, allowing it declaration of the function, allowing it to be called.to be called.

A function prototype must precede any A function prototype must precede any call or definition of a function, or a call or definition of a function, or a compiler errorcompiler error will occur. will occur.

Pattern:Pattern:

ReturnTypeReturnType NameName ( (ParameterDeclarationsParameterDeclarations));;

Page 16: Simple Functions

16

Example PrototypesExample Prototypes#include <iostream> // cin, cout, <<, >>, ...#include <cmath> // sqrt(), pow(), ...using namespace std;

double EllipseArea(double length, double width);double EllipseCircumference(double length, double width);

int main(){ cout << "\nTo compute the area and circumference" << "\n of an ellipse, enter its length and width: "; double length, width; cin >> length >> width; double area = EllipseArea(length, width); double circumference =

EllipseCircumference(length,width);

cout << "\nThe area is " << area << "\n and the circumference is " << circumference << endl;}

Page 17: Simple Functions

17

Function DefinitionsFunction Definitions

A function definition contains statements A function definition contains statements that dictate its behavior when it is called.that dictate its behavior when it is called.

A function must be defined in order to be A function must be defined in order to be called, or else a called, or else a linker errorlinker error will occur. will occur.

Pattern:Pattern:

ReturnTypeReturnType NameName ( (ParameterDeclarationsParameterDeclarations) ) { { StatementListStatementList } }

Page 18: Simple Functions

18

Example DefinitionsExample Definitions

const double PI = 3.14159;

double EllipseArea(double length, double width){ double halfLength = length/2.0, halfWidth = width/2.0; return PI * halfLength * halfWidth;}

double EllipseCircumference(double length, double width){ double halfLength = length/2.0, halfWidth = width/2.0; return 2.0 * PI * sqrt((pow(halfLength, 2.0) + pow(halfWidth,

2.0))/2.0);}

Page 19: Simple Functions

19

ParametersParameters

Parameters are function variables for Parameters are function variables for which the caller can specify values.which the caller can specify values.

Parameters are defined between the Parameters are defined between the parentheses of a function’s definition.parentheses of a function’s definition.

double EllipseArea(double length, double width){ double halfLength = length/2.0, halfWidth = width/2.0; return PI * halfLength * halfWidth;}

Page 20: Simple Functions

20

ArgumentsArguments

When a function is called, its caller can When a function is called, its caller can pass it values called pass it values called argumentsarguments which which are stored in the function’s parameters.are stored in the function’s parameters.

double area = EllipseArea(165, 135);

double EllipseArea(double length, double width){ double halfLength = length/2.0, halfWidth = width/2.0; return PI * halfLength * halfWidth;}

165 135

The function then The function then runsruns using its parameter using its parameter values.values.

Page 21: Simple Functions

21

Program StructureProgram Structure

C++ programs typically follow this C++ programs typically follow this pattern:pattern:#include directives#include directives

Function prototypesFunction prototypes

Main functionMain function

Function definitionsFunction definitions

Page 22: Simple Functions

22

OCD with FunctionsOCD with Functions

1. Specify the desired behavior of the program.1. Specify the desired behavior of the program.

2. Identify the objects needed.2. Identify the objects needed.

3. Identify the operations.3. Identify the operations.

a. If any operation is not predefined:

Write a function to perform it.

4. Organize objects and operations into an 4. Organize objects and operations into an algorithm.algorithm.

Page 23: Simple Functions

23

ProblemProblem

Suppose that in order to solve a different Suppose that in order to solve a different problem, a different program needs to problem, a different program needs to compute the area of an ellipse?compute the area of an ellipse?

Options:Options:– Copy-and-paste EllipseArea() from our Copy-and-paste EllipseArea() from our

previous program into the new program...previous program into the new program...

+Store EllipseArea() and Store EllipseArea() and EllipseCircumference() in a EllipseCircumference() in a library modulelibrary module, , so that programs can share them.so that programs can share them.

Page 24: Simple Functions

24

Library ModulesLibrary Modules

A library module consists of three files:A library module consists of three files:

• A A header fileheader file (usually with a (usually with a .h suffix) suffix) containing shareable function containing shareable function prototypesprototypes..

• An An implementation fileimplementation file (with suffix (with suffix .cpp) ) containing shareable function containing shareable function definitionsdefinitions..

• A documentation file (with suffix A documentation file (with suffix .doc) ) containing containing documentationdocumentation for the library. for the library.

Page 25: Simple Functions

25

ExampleExample

Since we are creating a library to share Since we are creating a library to share functions that describe an ellipse, functions that describe an ellipse, we name our library we name our library ellipseellipse, with , with

• header file header file ellipse.h,,

• implementation file implementation file ellipse.cpp, and, and

• documentation file documentation file ellipse.doc..

Page 26: Simple Functions

26

ellipse.hellipse.h

In In ellipse.h, we place the function , we place the function prototypesprototypes::

/* ellipse.h * Author: J. Adams. * Date: January 1998. * Purpose: Functions for computing ellipse attributes. */

double EllipseArea(double length, double width);double EllipseCircumference(double length, double width);// ... plus any others we want to provide while we’re at it

To use these functions, a program must To use these functions, a program must containcontain

#include ”ellipse.h”

Page 27: Simple Functions

27

ellipse.cppellipse.cpp

Their Their definitionsdefinitions are placed in are placed in ellipse.cpp::

/* ellipse.cpp * Author: J. Adams * Date: January 1998. * Purpose: Functions for computing ellipse attributes. */#include "ellipse.h"const double PI = 3.14159;

double EllipseArea(double length, double width){ double halfLength = length/2.0, halfWidth = width/2.0; return PI * halfLength * halfWidth;}

...

Page 28: Simple Functions

28

ellipse.cpp (cnt’d)ellipse.cpp (cnt’d)...

double EllipseCircumference(double length, double width){ double halfLength = length/2.0, halfWidth = width/2.0; return 2.0 * PI * sqrt((pow(halfLength, 2.0) + pow(halfWidth,

2.0))/2.0);}

This file can be compiled separately from This file can be compiled separately from any program that uses it.any program that uses it.

Page 29: Simple Functions

29

ellipse.docellipse.doc

The documentation file is a copy of the The documentation file is a copy of the header file, plus header file, plus function specificationsfunction specifications::

/* ellipse.doc * Author: J. Adams. * Date: January 1998. * Purpose: Functions for computing ellipse attributes. */

/********************************************************* * Compute the area of an ellipse. * * Receive: length, width, two double values. * * Return: the area of the corresponding ellipse. * *********************************************************/double EllipseArea(double length, double width);

Page 30: Simple Functions

30

ellipse.doc (cnt’d)ellipse.doc (cnt’d)

// ... first part of ellipse.doc

/********************************************************* * Compute the circumference of an ellipse. * * Receive: length, width, two double values. * * Return: the circumference of ellipse defined by * * length and width. * *********************************************************/double EllipseCircumference(double length, double width);

// ... plus any others we want to provide while we’re at it

By storing the documentation in a separate file, By storing the documentation in a separate file, we provide information on how to use the we provide information on how to use the library without cluttering its header file. library without cluttering its header file.

Page 31: Simple Functions

31

#include#include

When the C++ compiler processes a When the C++ compiler processes a #include directive, it directive, it

• opens the file named in the directive; andopens the file named in the directive; and

• replaces the replaces the #include directive with the directive with the contents of that file.contents of that file.

When the file contains function prototypes, When the file contains function prototypes, the effect of the the effect of the #include directive is to directive is to insert those prototypes into the program.insert those prototypes into the program.

Page 32: Simple Functions

32

TranslationTranslation

Translating a program into machine Translating a program into machine language consists of two steps:language consists of two steps:

1. 1. CompilationCompilation, in which the program is , in which the program is converted into the computer’s converted into the computer’s machine language; andmachine language; and

2. 2. LinkingLinking, in which any calls to functions , in which any calls to functions defined outside of that program are defined outside of that program are bound to function definitions.bound to function definitions.

Page 33: Simple Functions

33

Translation (cnt’d)Translation (cnt’d)

Compilation creates a Compilation creates a binarybinary object fileobject file (usually with a (usually with a .o or or .obj suffix). suffix).

Linking binds multiple object files into a Linking binds multiple object files into a single single binary executable filebinary executable file that can that can be run.be run.

int main()

{

// ...

}

C++Compiler

00100111010

10110001001

...

11101100100

file.cpp file.obj

Page 34: Simple Functions

34

LinkingLinking

00100111010

10110001001

...

11101100100

C++Linker

00100111010

10110001001

...

11101100100

11100101011

10010001000

...

10101101101

01101101011

11010101001

...

00101100100

file1.obj

file.exe

11100101011

10010001000

...

10101101101

file2.obj

01101101011

11010101001

...

00101100100

fileN.obj

Page 35: Simple Functions

35

Using a LibraryUsing a LibraryTo use the library, a program mustTo use the library, a program must

• #include its header file (usually above the #include its header file (usually above the main function), inserting the function main function), inserting the function prototypes so that they can be called.prototypes so that they can be called.

• be linked to its implementation file.be linked to its implementation file.

Failure to do either of these produces an Failure to do either of these produces an error.error.

Page 36: Simple Functions

36

ExampleExample#include <iostream> // cin, cout, <<, >>, ...using namespace std;#include "ellipse.h" // insert ellipse

prototypesint main(){ cout << "\nTo compute the area and circumference" << "\n of an ellipse, enter its length and width: "; double length, width; cin >> length >> width; double area = EllipseArea(length, width); double circumference =

EllipseCircumference(length,width); cout << "\nThe area is " << area << "\n and the circumference is " << circumference << endl;}

Page 37: Simple Functions

37

Compiler ErrorsCompiler Errors

A compiler error occurs if a program A compiler error occurs if a program calls a function for which no prototype calls a function for which no prototype is given. is given.

This can occur if you call a library This can occur if you call a library function and neglect to function and neglect to #include the the header file containing its prototype.header file containing its prototype.

- You’ll be trying to - You’ll be trying to useuse a function that a function that has not been has not been declareddeclared..

Page 38: Simple Functions

38

Linker ErrorsLinker Errors

A A linker errorlinker error occurs if a program calls a occurs if a program calls a function for which the linker is unable to function for which the linker is unable to find a definition.find a definition.

This can occur if a program calls a function This can occur if a program calls a function but the linker is not told to use the but the linker is not told to use the library implementation file or object file library implementation file or object file containing that function’s definition.containing that function’s definition.

How this is done varies from platform to How this is done varies from platform to platform, but often involves a platform, but often involves a project fileproject file..

Page 39: Simple Functions

39

OCD with LibrariesOCD with Libraries

1. Specify the desired behavior of the program.1. Specify the desired behavior of the program.

2. Identify the objects needed.2. Identify the objects needed.

3. Identify the operations.3. Identify the operations.

a. If an operation is not predefined:a. If an operation is not predefined:

Write a function to perform it.Write a function to perform it.

b. If an operation is likely to be reuseable someday:

Store its function in a library and access it from there.

4. Organize objects and operations into an algorith4. Organize objects and operations into an algorithm.m.

Page 40: Simple Functions

40

SummarySummaryFunctions provide a programmer with a Functions provide a programmer with a

means of extending C++ with new means of extending C++ with new operations that are not predefined in the operations that are not predefined in the language.language.

A function prototype must precede its call, A function prototype must precede its call, or a compiler error will occur.or a compiler error will occur.

A function definition must be provided, A function definition must be provided, or a linker error will occur.or a linker error will occur.

Libraries provide a means of storing functions Libraries provide a means of storing functions so that multiple programs can use them.so that multiple programs can use them.

Page 41: Simple Functions

41

Summary (Cnt’d)Summary (Cnt’d)

• Libraries consist of three files: for function Libraries consist of three files: for function prototypes, definitions, and prototypes, definitions, and documentation.documentation.

To use a library, a program mustTo use a library, a program must

• #include its header file, or a compiler #include its header file, or a compiler error will occur.error will occur.

• Be linked to its implementation file (or the Be linked to its implementation file (or the object file produced by compiling the object file produced by compiling the implementation file), or a linker error will implementation file), or a linker error will occur.occur.