Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software...

62
Functions Chapter 4
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    214
  • download

    0

Transcript of Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software...

Functions

Chapter 4

C++ An Introduction to Programming, 3rd ed.2

Objectives

Study software development using OCDTake a first look at building functionsStudy how a function is calledInvestigate how a function executesShow design process for functionsTake a first look at sequence, selection, repetitionIntroduce the if, for, and while statementsStudy libraries and their useIntroduce computability theoryTake a first look at class methods

C++ An Introduction to Programming, 3rd ed.3

ProblemTwo scales used to measure temperature are the

Fahrenheit and Celsius scales. A program is needed to convert temperatures in Fahrenheit to the equivalent Celsius temperatures.

General

Behavior

For conversion to Celsius,enter Fahrenheit temp: 99

Equivalent Celsius tem is 99.9

C++ An Introduction to Programming, 3rd ed.4

Objects

DescriptionSoftware Objects

Type Kind Namescreen ostream varying cout

prompt string constant

Fahrenheit temp double varying tempFahrenheit

keyboard istream varying cin

Celsius temp double varying tempCelsius

descriptive text string constant

C++ An Introduction to Programming, 3rd ed.5

Operations

Formula used

i. Display string on screen

ii. Read number from keyboard

iii. Compute Celsius equivalent of Fahrenheit

a. Perform real subtraction

b. Perform real division

iv. Display a number on screen

32.0

1.8

FC

C++ An Introduction to Programming, 3rd ed.6

Algorithm

1. Output a prompt for a Fahrenheit temperature to cout.

2. Input tempFahrenheit from cin.

3. Calculate tempCelsius = (tempFahrenheit – 32.0) / 1.8.

4. Output tempCelsius (and descriptive text) to cout.

Coding and Testing • Note source code in Figure 4.1• Note sample runs for Figure 4.1

C++ An Introduction to Programming, 3rd ed.7

#include <iostream>using namespace std;

double dFahrToCelsius(double dTempFahr); // FUNCTION PROTOTYPE

int main()

{ cout << "212F => " << dFahrToCelsius(212) << endl << "32F => " << dFahrToCelsius(32) << endl;}

double dFahrToCelsius(double dTempFahr){

double dCelsius;dCelsius = (dTempFahr - 32.0) / 1.8;return dCelsius;

}

C++ An Introduction to Programming, 3rd ed.8

Temperature Conversion with Functions

Consider the need for use of this task by other programs

We can construct a function that encapsulates the conversion code

Note source code Figure 4.2• Uses a function to do the conversion

C++ An Introduction to Programming, 3rd ed.9

Comparison of Versions

Program of Figure 4.2 has same output as that of Figure 4.1• Flow of execution is very different.

C++ An Introduction to Programming, 3rd ed.10

Function Definitions

Function definition • Contains statements that dictate its behavior

when it is called.

Function must be defined in order to be called• Else a linker error will occur.

Pattern: ReturnType Name (ParameterDeclarations) { StatementList }

C++ An Introduction to Programming, 3rd ed.11

Example Definitionsconst PI = 3.14159;

double EllipseArea(double length, double width);{

double dArea, dHalfLength, dHalfWidth;

halfLength = length/2.0; halfWidth = width/2.0;

dArea = PI * halfLength * halfWidth;

return dArea;}

C++ An Introduction to Programming, 3rd ed.12

Functions Are Subprograms

Same steps for program design can be used for function design

1. Behavior

2. Objects

3. Operations

4. Algorithm

5. Coding

6. Testing, execution, debugging

7. Maintenance

Behavior for functions will also include

Receive values from calling function

Return value to calling function

Behavior for functions will also include

Receive values from calling function

Return value to calling function

C++ An Introduction to Programming, 3rd ed.13

Behavior and Objects

Receive from caller a Fahrenheit temp

Do the conversion with the correct formula

Return to caller the equivalent temp

DescriptionSoftware Objects

Type Kind Movement Name

a Fahrenheit temp

double varying received (in) tempFahr

equivalent Celsius temp

double varying returned (out)

C++ An Introduction to Programming, 3rd ed.14

Parameters

Function variables for which the caller can specify values.

Defined between the parentheses of a function’s definition.

double fahrToCelsius(double tempFahr)

{

return (tempFahr - 32.0) / 1.8;

}

C++ An Introduction to Programming, 3rd ed.15

Arguments

When a function is called• Caller can pass it values called arguments • Stored in the function’s parameters.

double newTemp = fahrToCelsius (212)

double fahrToCelsius(double tempFahr)

{

return (tempFahr - 32.0) / 1.8;

}

The function then runs using its parameter values.

212

C++ An Introduction to Programming, 3rd ed.16

Operations

Operations• Real subtraction (tempFahr – 32.0)

• Real division ((tempFahr – 32.0)/1.8)

• Return a real value

double fahrToCelsius(double tempFahr)

{

return (tempFahr - 32.0) / 1.8;

}

C++ An Introduction to Programming, 3rd ed.17

Design

Specification of the function• Determines the form of the function heading

• Return value• Name• Parameters

Algorithm of the function• Determines the content of the function body

• Input, Output• Branching, looping

C++ An Introduction to Programming, 3rd ed.18

Testing, Execution, Debugging

To test a function, we need a driver program• Figure 4.3 shows the driver program

Note also the test run

C++ An Introduction to Programming, 3rd ed.19

Function Prototype

Acts as a declaration of the function• Allowing it to be called

Function prototype must precede any call or definition of a function• Else a compiler error will occur• Compiler must know of a function's existence

Pattern:ReturnType Name (ParameterDeclarations);

C++ An Introduction to Programming, 3rd ed.20

Example 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;} To call a function, use the name of the

function as if it is an expression

To call a function, use the name of the function as if it is an expression

C++ An Introduction to Programming, 3rd ed.21

Local Variables

Our example only used the parameter tempFahrMany functions need other variables or constants

double windChill(double tempFahr, double windSpeed) { double v_part = -35.75 + 0.4275 * tempFahr; return 35.74 + 0.6215 * tempFahr + v_part *

pow(windSpeed, 0.16);}

C++ An Introduction to Programming, 3rd ed.22

Functions That Return Nothing

Often a program has a task that is repeated often• Print out some values• Retrieve values from a file

This is done with void functions

Note the printAsMoney ( ) function in Figure 4.5

Note the sample runs

C++ An Introduction to Programming, 3rd ed.23

Functions That Use Selection

Problem:Write a function, that given two real values, returns the minimum of the two values.

Behavior• Receive two real values from caller• If first is less than second, return first value• Otherwise return second value

C++ An Introduction to Programming, 3rd ed.24

Functions That Use SelectionObjects

DescriptionSoftware Objects

Type Kind Movement Name

first value double variable received first

second value double variable received second

minimum value double variable returned

C++ An Introduction to Programming, 3rd ed.25

Functions That Use Selection

Operationsi. Receive two real values from the function’s caller

ii. Compare two real values to see if one is less than the other

iii. Return the first value

iv. Return the second value

v. Select either iii or iv (but not both), based on the result of ii

AlgorithmIf first < second

return first;

otherwise

return second.

C++ An Introduction to Programming, 3rd ed.26

Functions That Use Selection

Coding• View Figures 4.6, 4.7

Testing• Note sample runs

C++ An Introduction to Programming, 3rd ed.27

Function Behavior

Determined by the statements within the function.

Statements fall into one of three categories:• Statements that simply execute in sequence.• Statements that select one of several

alternatives.• Statements that repeat another statement.

C++ An Introduction to Programming, 3rd ed.28

Sequential Execution

C++ statements are executed • One after another • In sequence{ Statement1

Statement2

... StatementN

}

The C++ compound statement (or block) • A statement for eliciting sequential

execution of a series of statements.

by default:

C++ An Introduction to Programming, 3rd ed.29

Selective ExecutionConsider a requirement that a statement be executed • Selectively• Based on a condition

(a boolean expression): if (Condition) Statement1

[ else Statement2 ]

if (Condition) Statement1

[ else Statement2 ]

The C++ if statement • For eliciting selective execution of a statement• Allowing a program to choose to execute either

Statement1 or Statement2, but not both.

C++ An Introduction to Programming, 3rd ed.30

C++ StatementsNote that a Statement can be either• Single

statement, • Compound

statement:

if (score > 100 || score < 0) { cerr << “Invalid score!\n”; exit(1); } else if (score >= 60) grade = ‘P’; else grade = ‘F’;

if (score > 100 || score < 0) { cerr << “Invalid score!\n”; exit(1); } else if (score >= 60) grade = ‘P’; else grade = ‘F’;

To select two or more statements• Must be wrapped in curly-braces { }• Forms a compound statement.

C++ An Introduction to Programming, 3rd ed.31

Nested ifs

Syntax calls for a statement• Could be an if statement if (abs(x-7) < epsilon) if (x < 7) cout << "x approaches 7 from left"; else if (x > 7) cout << "x approaches 7 from right";else cout << "x not close to 7";

if (Condition) Statement1

[ else Statement2 ]

if (Condition) Statement1

[ else Statement2 ]

Which else goes with which if??

Which else goes with which if??

In a nested if statement, an else is matched with the nearest preceding unmatched if

In a nested if statement, an else is matched with the nearest preceding unmatched if

C++ An Introduction to Programming, 3rd ed.32

Nested ifs

The result may not be what you want• Use curly brackets to make a compound

statement or block

if (abs(x-7) < epsilon) { if (x < 7) cout << "x approaches 7 from left"; else if (x > 7) cout << "x approaches 7 from right"; }else cout << "x not close to 7";

C++ An Introduction to Programming, 3rd ed.33

Functions that Use Repetition

Problem: The factorial of a nonnegative integer n, is denoted by n! and defined by

Write a function that, given an integer ≤ 0, computes n factorial

1 if n = 0!

1 2 ... if n > 0n

n

C++ An Introduction to Programming, 3rd ed.34

Objects, Operations

Operationsi. Check the preconditionii. Declare and initialize two integer variables (product and count)iii. Multiply two integers (product and count) and assign the result

to an integer (product)iv. Increment an integer variable (count)v. Repeat Operations iii and iv so long as count is less than or

equal to n

DescriptionSoftware Objects

Type Kind Movement Name

nonnegative integer

int variable received n

the running product

int variable returned product

the counter int variable local count

C++ An Introduction to Programming, 3rd ed.35

Algorithm, Source Code, Testing

1. Initialize product to 1.2. Repeat the following for each value of count in the range 2 to n:

Multiply product by count.

3. Return product.Note source code of Figures 4.8, 4.9 which implements the algorithm and tests the functionView sample runs

C++ An Introduction to Programming, 3rd ed.36

#include <iostream>using namespace std;int factorial(int n);

int main(){

int nTheNumber;cout << "To compute n!, enter n: ";cin >> nTheNumber;cout << nTheNumber << "! = " << factorial(nTheNumber) << endl;

}

/* factorial computes the factorial of a nonnegative integer.** Receive: n, an integer* Precondition: n is nonnegative* Return: n!*************************************************************/#include <cassert> // assert()using namespace std;int factorial(int n){

assert(n >= 0);int nProduct = 1;for (int nCount = 2; nCount <= n; nCount++) nProduct *= nCount;return nProduct;

}

C++ An Introduction to Programming, 3rd ed.37

Repetitive Execution

Consider a requirement that a statement be repeated• Repetition being controlled by a condition:

for (InitializerExpr; LoopCondition; IncrementExpr) Statement

for (InitializerExpr; LoopCondition; IncrementExpr) Statement

The C++ for statement • For eliciting repetitive execution of a statement, • allowing a program to repeat the execution of Statement.

C++ An Introduction to Programming, 3rd ed.38

The for Loop for (InitializerExpr;

LoopCondition; IncrementExpr)

Statement

for (InitializerExpr; LoopCondition; IncrementExpr)

Statement

Statement will be executed so long as LoopCondition is true.

InitializerExpr

LoopCondition

Statement

IncrementExpr

F

T

Statement is often called the body of the loop.

C++ An Introduction to Programming, 3rd ed.39

The for Loop

for (InitializerExpr; LoopCondition; IncrementExpr)

Statement

for (InitializerExpr; LoopCondition; IncrementExpr)

Statement

Each execution of LoopCondition, Statement, IncrementExpr

is called one repetition or iteration of the loop.

InitializerExpr

LoopCondition

Statement

IncrementExpr

F

T

C++ An Introduction to Programming, 3rd ed.40

The for Loop for (InitializerExpr; LoopCondition; IncrementExpr)

Statement

for (InitializerExpr; LoopCondition; IncrementExpr)

Statement

When LoopCondition becomes false,• Control proceeds to the

next statement.

InitializerExpr

LoopCondition

Statement

IncrementExpr

F

T

Note: if the LoopCondition is initially false, then the body of the loop will not be executed even once.

Note: if the LoopCondition is initially false, then the body of the loop will not be executed even once.

C++ An Introduction to Programming, 3rd ed.41

Counting

The “normal” use of the for loop is to count:

for (int count = 1; count <= limit; count++) cout << count << endl;

Output (suppose limit == 5):

1 2 3 4 5

C++ An Introduction to Programming, 3rd ed.42

Nested Loops

Loops can also be nested: for (int val1 = 1; val1 <= limit1; val1++) for (int val2 = 1; val2 <= limit2; val2++) cout << val1 << ‘*’ val2 “ = “ << val1 * val2 << endl;

Output (suppose limit1 == 2, limit2 == 3):

1*1 = 1 1*2 = 2 1*3 = 3 2*1 = 2 2*2 = 4 2*3 = 6

C++ An Introduction to Programming, 3rd ed.43

Counting Loops

The for loop is normally used to count through a range of values:

for (int count = first; count <= last; count++) Statement

for (int count = first; count <= last; count++) Statement

Such a loop will count • From first • To last (inclusive), • Executing Statement• Once for each value in the range first..last.

C++ An Introduction to Programming, 3rd ed.44

Problem with for Loop

Consider a program to process several input values• It does not know how many input values are

coming• How to run a counting loop to handle this

situation??

Solution• Use the while loop• The body of the loop executes repeatedly

while the loop condition is true

C++ An Introduction to Programming, 3rd ed.45

The while Loop

For such situations, C++ provides the more readable while loop,

pattern is:

while (Expression) Statement

Expression

T

F

Statement

Statement can be either a single or compound C++ statement.

Repetition continues so long as Expression is true!

Note use of

while loop in driver for testing

factorial, Figure 4.10

C++ An Introduction to Programming, 3rd ed.46

Computability Theory

We have used sequence, selection, and repetition

The set of all operations possible with sequence is a proper subset of all operations built with sequence and selection

Similarly with sequence, selection, and repletion

C++ An Introduction to Programming, 3rd ed.47

Computability Theory

Note the Venn Diagram which visualizes the concept

C++ An Introduction to Programming, 3rd ed.48

Computability Theory

This branch of computer science investigates theoretically questions such as:

What can or cannot be computed?

How can functions be classified?• What relationships exist among those classes?

What is the most efficient algorithm for solving a particular problem?

Problem Session

Working in groups of two,

solve the following problem...

C++ An Introduction to Programming, 3rd ed.50

Problem

Consider an eight-function calculator• Allows the user to perform addition,

subtraction, multiplication, division, exponentiation, base-ten logarithm, factorial, and quit operations

Use OCD (Object Centered Design)Behavior:• User enters symbol for the operation• Program displays prompts for operand(s)• Results calculated, displayed

C++ An Introduction to Programming, 3rd ed.51

Objects

DescriptionSoftware Objects

Type Kind Name

C++ An Introduction to Programming, 3rd ed.52

Operations

Description Name

Predefined? Library Operator

Use description to fill in chart for operations.

C++ An Introduction to Programming, 3rd ed.53

Algorithm and Coding

Work together to determine the steps necessary to have the objects manipulated by the operations

Write the source code• Compile and Link• Test the program

C++ An Introduction to Programming, 3rd ed.54

An Introduction to Libraries

We seek to easily reuse handy functions we developLibraries are files containing items to be shared by different programs• Functions logically grouped into libraries by the

task that they do

Header file contains declarations, prototypes (also called the interface file)Note Figure 4.12 – a header file for library Heat

C++ An Introduction to Programming, 3rd ed.55

An Introduction to Libraries

Programs which will use functions from the Heat library must specify#include "Heat.h"The implementation file includes the definitions of these library functions

Note the source code of how the Heat.cpp file appears, Figure 4.13

C++ An Introduction to Programming, 3rd ed.56

An Introduction to Libraries

Items in the .cpp file that are declared in the .h file can be accessed by • any program that uses the #include directive • and links to the implementation file

Items in the .cpp file NOT declared in the .h file CANNOT be accessed outside the implementation file• Even if the #include is used

C++ An Introduction to Programming, 3rd ed.57

An Introduction to Libraries

Documentation file is a copy of the header file annotated with• documentation of the objects• function prototype specifications

Once the library is constructed it can be used as shown in Figure 4.15

C++ An Introduction to Programming, 3rd ed.58

Benefits of Libraries

Functions are reusable

Libraries hide implementation details

Programs are easier to maintain

Separate compilation

Independent coding

Testing is simplified

C++ An Introduction to Programming, 3rd ed.59

OBJECTive Thinking:Class Methods

Class methods are function members• A mechanism for building a new operation for

a class type

Categories of methods• Class method – defines a message that can

be sent to a class• Instance method – defines a message sent to

an object (an instance of a class)

C++ An Introduction to Programming, 3rd ed.60

A Temperature Class Method

#include <iostream>using namespace std;#include "Temperature.h"int main(){

cout << "To convert Fahrenheit to Celsius,\n" << " enter a Fahrenheit temperature: ";double fahrTemp;cin >> fahrTemp;double celsTemp = Temperature::fahrToCels(fahrTemp);cout << "The equivalent temperature is " << celsTemp << endl;

}

Message is sent to the class, not to an object.

Message is sent to the class, not to an object.

Note class methods in declaration of Figure 4.17

Note class methods in declaration of Figure 4.17

Note the scope operator

Note the scope operator

C++ An Introduction to Programming, 3rd ed.61

A Temperature Class Method

As we wrapped variable declarations in a class, we can also wrap function prototypes

When keyword static prefaces class method – this specifies a class method

When keyword static not used, the method is an instance method

When the method is defined, note the use of the class name and scope operator

Class methods must not access instance variables

C++ An Introduction to Programming, 3rd ed.62

A Temperature Class Method

Variables within a class may also be specified as static variables• This makes them class variables• Each instance of a class shares class variables• Each instance of a class has its own instance variables

Class methods may access class variables

Instance methods may access both• Class variables• Instance variables