Lecture 8: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.

Post on 17-Jan-2016

218 views 0 download

Tags:

Transcript of Lecture 8: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.

Lecture 8: Top-Down Design with Functions

COS120 Software Development Using C++ AUBG, COS dept

2

Lecture Contents:

Top-Down Design and step-wise refinement with structure charts

Functions topics: prototype, call, definition Functions with input argument(s) and no return value Functions with input argument(s) and returning a single

value as a result The return statement Library functions

3

Top-Down design

There exist problems whose solving algorithms are too complicated, more complex than those already solved.

Then developer breaks up problem into sub problems to solve and develop program solution.

If necessary, some sub problems are to be broken up into sub sub problems and so on.

The process described is called Top-Down Design or Step-Wise refinement and may illustrate using structure charts.

4

Summary on functions

Prototype statement: void fname(void);

Call statement: fname( );

Function Definition: void fname(void){ <local declarations> <executable statements>}

5

Conclusion on functions:

Why to use functions?

(two important reasons)

1. Dividing a program into functions is one of the major principles of structured programming.

2. Using functions results in reduced program size.

6

Valid reasons to create a routine:

Reduce complexity– “Properly designed functions permit to ignore how a job’s done. Knowing

what is done is sufficient.”

B.Kernighan & D.Ritchie

– “A function provides a convenient way to encapsulate some computation, which can then be used without worrying about its implementation. ”

B.Kernighan & D.Ritchie

Avoid duplicate code– Usually functions are specified to be called many times.

7

Details on functions

Three important topics when dealing with functions:

        prototype (signature) statement

        function call statement

        function definition

8

Functions with input arguments

Input arguments are used to carry information into the function.

Function may return at most one value.

Output arguments are used to return data from function to caller.

9

General notation – function with no argument(s)

Prototype: void fname(void);

Call: fname();

Definition: void fname(void){

<local declarations><executable statements>

}

10

General notation – function with argument(s) and no return value

Prototype: void fname(<formal parameters declaration list>);

Call: fname(<list of actual arguments>);

Definition: void fname(<formal parameters declaration list>){

<local variable declarations><executable statements>

}

11

Example – to display a real number in a box

Problem: to display a number in a box

No Input: the number to display is fixed to 35.6789Output: input number to be displayed in a box composed of 5

lines:

1st line: 11 stars ***********

2nd line: star, 9 spaces, star * *

3rd line: star, space, 7 digits, space, star * 35.6789 *

4th line: star, 9 spaces, star * *

5th line: 11 stars ***********

12

Possible solutions

Spaghetti code version– No need to comment

Function with no parameter and no return valueFunction definition: Function prototype:void NumInBox(void) void NumInBox(void); {

cout << "\n***********";cout << "\n* *";cout << "\n* 35.6789 *"; Function call: cout << "\n* *"; NumInBox();cout << "\n***********";cout << "\n";

}

13

Functions may get

input data

14

Intro to functions with params

We need a more flexible tool used to display any number in a box, not just and only the real number 35.6789.

We need to use the same template as the NumInBox() function.

We need a tool to transfer the number to be displayed into the function.

The tool exists and it is known as parameter passing mechanism OR in other words: Input arguments are used to carry information into the function.

15

Example – to display a real number in a box

Problem: to display a number in a box

Input: any real number

Output: input number to be displayed in a box of 5 lines:

1st line: 11 stars ***********

2nd line: star, 9 spaces, star * *

3rd line: star, space, 7 digits mask, space, star * xxxxxxx *

4th line: star, 9 spaces, star * *

5th line: 11 stars ***********

16

Example – to display a real number in a box

Function definition:void NumInBox(double num) {cout << "\n***********";cout << "\n* *";cout << "\n* " << num << " *";cout << "\n* *";cout << "\n***********";cout << "\n";

}

17

Example – to display a real number in a box

Function definition:void NumInBox(double num) {

cout << "\n***********"; cout << "\n* *";

cout << "\n* " << setw(7) << setfill('0') << num << " *";cout << "\n* *";cout << "\n***********";cout << "\n";

}

18

Example – to display a real number in a box

Function prototype:

void NumInBox(double num);

19

Example – to display a real number in a box

Function call in three versions:NumInBox(3.14);NumInBox(2.78);

//---------------------------------double x; x = 35.68; NumInBox(x);

//---------------------------------double y = 2.78;NumInBox(y+3.);

20

Example – full program on back page of the handout

#include <iostream>#include <iomanip>using namespace std;void NumInBox(double num); // user defined function’s prototypevoid main() // source text of function main{ NumInBox(3.14); NumInBox(2.78);  double x; x = 35.68; NumInBox(x);  double y = 2.78; NumInBox(y+3); }void NumInBox(double num) { // user defined function definition cout << "\n***********"; cout << "\n* *"; cout << "\n* " << setw(7) << setfill('0') << num << " *"; cout << "\n* *"; cout << "\n***********"; cout << "\n"; }

21

Functions may

return data

22

Function(s) may return values

The NumInBox(double num) function is called to do its job and that is all. The argument is displayed in a box. No need to communicate with the calling program unit.

There exist problems when the job done by the function has to be returned to the calling unit as a result value.

The mechanism to achieve this effect is based on a return statement located in the function end.

23

General notation – function with argument(s) and return value

Prototype: ftype fname(<formal parameters declaration list>);

Call: fname(<list of actual arguments>);

Definition:ftype fname(<formal parameters declaration list>){

<local variable declarations><executable statements>return (<expression>);

}

24

The return statement

Syntax:

return;

return <expression>;

return(<expression>);

25

Practical problem

Build a function FindArea(…) to evaluate (return) the area of a circle: 1 formal parameter (radius) and a return value

Write a driver program /function main()/ to test the function FindArea(…)

See solution on next slide

26

Problem: the area of a circledouble FindArea(double rad);

Prototype: double FindArea(double rad);

Call: cout << FindArea(100.0);double x;x = FindArea(200.); cout <<

x;

Definition: double FindArea(double rad){ return 3.14 * rad * rad;}

27

Previous lecture reminder

Title:

Top-Down Design Using Functions

Source: Friedman/Koffman, Chapter 03

Have a quick look at coming slides to refresh your knowledge on functions

Top-Down Design with Functions and Classes

Chapter 3

29

3.3 Top-Down Design and Structure Charts

D raw aC irc le

D rawin te rsec tin g

lin es

D raw ab ase

D raw aTrian g le

D rawin te rsec tin g

lin es

D raw afig u re

Original Problem

Detailed

subproblems

Level 0

Level 1

Level 2

30

3.4 Functions without Arguments

– Functions used in Top-Down Design– main() is just a function

• called by OS

– C++ program is a collection of Functions• top level function is called the main()• lower level functions

– User Defined or Libraries– Example StkFigMn.cpp

31

StickFigure.cpp

// File: stickFigure.cpp// Draws a stick figure

#include <iostream>using namespace std;

// Functions used ...

void drawCircle(); // Draws a circlevoid drawTriangle(); // Draws a trianglevoid drawIntersect(); // Draws intersecting linesvoid drawBase(); // Draws a horizontal line

32

StickFigure.cpp

int main(){

// Draw a circle.drawCircle();

// Draw a triangle.drawTriangle();

// Draw intersecting lines.drawIntersect();

return 0;}

33

Function Calls

– We can call a function and get results without knowing the implementation of that function.• pow(x, y) returns x to the yth power.

– For now, we need not know exactly how a function is implemented.

– However, we do need to know how to use the function.

34

Function Calls

– This general form of a function call:

function-name( <optional argument-list> );– Example function call:

drawCircle( );– The function name is drawCircle – No arguments to the function

35

Function Prototype

– This general form of a function prototype:

type function-name( <optional argument-list> );

– Example function prototype:

void skipThree( );

– Type

• int - float - char

– Name

– ( );

– Descriptive comment

36

Function Definition

– General form of a function definition:

type function-name( <optional argument-list> )

{

local-declarations - function body

executable-statements

}– Example function definition:

void drawTriangle( )

37

Function Definition

void drawTriangle()

{

// Draw a triangle.

drawIntersect();

drawBase();

}

function header

function body

38

StickFigure.cpp

// Draws a circlevoid drawCircle(){ cout << " * " << endl; cout << " * *" << endl; cout << " * * " << endl;} // end drawCircle

39

StickFigure.cpp

void drawCircleChar(char symbol){ cout << " " << symbol << " " << endl; cout << " " << symbol << " " << symbol << endl; cout << " " << symbol << " " << symbol << endl;}

// Draws a trianglevoid drawTriangle(){ drawIntersect(); drawBase();}

40

StickFigure.cpp

// Draws intersecting linesvoid drawIntersect(){ cout << " / \\ " << endl; cout << " / \\ " << endl; cout << " / \\" << endl;}

// draws a horizontal linevoid drawBase(){ cout << "-------" << endl;}

41

Order of Execution

int main()

{

drawCircle();

drawTriangle();

drawIntersect();

return 0;

}

void drawCircle()

{

cout << “ * “ << endl;

cout << “ * * “ << endl;

cout << “ * * “ << endl;

}

42

Function Advantages

– Program team on large project

– Simplify tasks

– Each Function is a separate unit

– Top-down approach

– Procedural abstraction

– Information hiding

– Reuse (drawTriangle)

43

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

44

Displaying User Instructions

We still have not covered passing in and out of a function

Following example shows displaying info– instruct(); function call in main

45

Instruct.cpp

// DISPLAYS INSTRUCTIONS TO THE USER // OF AREA/CIRCUMFERENCE PROGRAM

void instruct(){ cout << "This program computes the area and " << endl; cout << "circumference of a circle. " << endl << endl; cout << "To use this program, enter radius of the " << endl; cout << "circle after the prompt" << endl; cout << "Enter the circle radius: " << endl << endl; cout << "The circumference will be computed in the ” << endl; cout << "units of measurement as radius. The area " << endl; cout << "will be computed in the same units squared." << endl;}

46

Program Output

This program computes the area and circumference of a circle.

To use this program, enter the radius of the circle after the prompt

Enter the circle radius:

The circumference will be computed in the same units of measurement as the radius. The area will be computed in the same units squared.

47

3.5 Functions with Input Arguments

– Functions used like building blocks

– Build systems one functions at a time• Stereo Components

– Use function return values and arguments to communicate between functions

– Discuss AreaMain.cpp• Flow of arguments and returns

48

Function Call

Form: fname(<actual arg list>);

Example: scale(3.0, z);

49

Function Return

Functions must return a value unless declared as void

Form: return <expression>;

Example: return x*y;

50

Function Definition

Form: type fname(<formal arg list>) {

function body }

Example: float scale(float x, int n){

float scaleFactor;scaleFactor = pow(10, n);return (x * scaleFactor);

}

51

Function Prototype

Form: type fname(<formal arg type list> );

Example: float scale(float x, int n);

52

TestScale.cpp

// Tests function scale. #include <iostream>#include <cmath>

using namespace std;

// Function prototype float scale(float, int);

53

TestScale.cpp int main(){

float num1; int num2;

// Get values for num1 and num2 cout << "Enter a real number: "; cin >> num1; cout << "Enter an integer: "; cin >> num2;

// Call scale and display result. cout << "Result of call to function scale is "; cout << scale(num1, num2) << endl;

return 0;}

54

TestScale.cpp

float scale(float x, int n){ float scaleFactor; scaleFactor = pow(10, n); return (x * scaleFactor);}

55

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 Parameter

3.0 x

z n

56

Argument / Parameter List Correspondence

float scale(float x, int n)

{

float scaleFactor;

scaleFactor = pow(10, n);return (x *

scaleFactor);

}

57

Argument / Parameter List Correspondence

Function call: scale(x + 2.0, y);

Actual Argument Formal Parameter

x + 2.0 x

y y

58

Argument / Parameter List Correspondence

Function call: scale(y, x);

Actual Argument Formal Parameter

y x

x y

Watch for type matches in formal parameters and actual arguments

59

Key Points

The substitution of the value of an actual argument in a function call for its corresponding formal argument is strictly positional. That is, the value of the first actual argument is substituted for the first formal argument; the second and so on

60

Key Points

The names of these corresponding pairs of arguments are no consequence in the substitution process. The names may be different, or they may be the same.

The substituted value is used in place of the formal argument at each point where that argument appears in the called function.

61

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

62

Scope of Names

Positional correspondence Type consistent is key because of positional

correspondence– Argument types– Return types

63

Scope of Names

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

64

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

65

Common Programming Errors

– Function Prototype & Definition Mismatches• Both are the same except for the ;

– Return Statements• “Return value expected”• “Function should return value”

– Missing Object Name in Call to Member Function

– Missing #include– Type Mismatches

66

Exercise 8.1

Define a function and Build a program:

to compute the area of a circle

double FindArea(double rad);

67

Exercise 8.2

Define a function and Build a program:

to compute the circumference of a circle

double FindCircum(double rad);

68

Exercise 8.3

Define a function and Build a program:

to compute the area of a square

int FindSqArea(int side);

69

Exercise 8.4

Define a function and Build a program:

to compute the perimeter of a square

int FindSqPerim(int side);

70

Exercise 8.5

Define a function and Build a program:

to solve the Miles-to-Kilometers conversion problem

double ConvMilesToKms(double kms);

71

Library functionsList of some Mathematical Library Functions

(#include <cmath>, data type double):Function Purpose (return value)sqrt(x) Square root (x>=0)sin(x) Sine of angle x (in radians)pow(x,y) xy (power operator)cos(x) Cosine of angle x (in radians)exp(x) ex (e=2.71828…)tan(x) Tangent of angle x (in radians)log(x) Natural logarithm (x>0)ceil(x) Smallest integral not < than xlog10(x) Base-10 logarithm (x>0)floor(x) Largest integral not > than x

72

Library functionsList of some Character Library Functions (#include <cctype>)Function Purpose (return value)char tolower(char c)

Returns lowercase letter if c is uppercase. Otherwise, returns c.char toupper(char c)

Returns uppercase letter if c is lowercase. Otherwise, returns c.bool isalpha(char c)

Returns true if c is a letter (‘a’ … ‘Z’), otherwise false.bool isalnum(char c)

Returns true if c is a letter or a digit, otherwise false.bool isdigit(char c)

Returns true if c is a digit (‘0’ … ‘9’), otherwise false.bool isxdigit(char c)

Returns true if c is a hex digit (‘0’…’9’, ‘a’… ‘f’, ‘A’…’F’).bool isspace(char c)

Returns true if c is a space or tab(‘\t’) or new line (‘\n’).

73

Before lecture end

Lecture:

Top-Down Design using Functions

More to read:

Friedman/Koffman, Chapter 03

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3: Top-Down Design with Functions and Classes

Problem Solving,

Abstraction, and Design using C++ 5e

by Frank L. Friedman and Elliot B. Koffman

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 75

Functions with Input Arguments

• Functions used like building blocks

• Build systems one function at a time– E.g. stereo components

• Use function arguments to carry information into function subprogram (input arguments) or to return multiple results (output arguments)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 76

Functions with Input Arguments

• Arguments make functions versatile

• E.g.:

rimArea = findArea(edgeRadius) -

findArea(holeRadius);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 77

void Functions with Input Arguments

• Give data to function to use

• Don’t expect function to return any result(s)

• Call format:

fname (actual-argument-list);

• E.g.:

drawCircleChar(‘*’);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 78

drawCircleChar(‘*’);

void drawCircle(char symbol)

{

cout << “ “ << symbol << endl;

cout << “ “ << symbol << “ “ << symbol << endl;

cout << “ “ << symbol << “ “ << symbol << endl;

} // end drawCircle

‘*’symbol

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 79

Functions with Arguments and a Single Result

• Functions that return a result must have a return statement:

Form: return expression;

Example: return x * y;

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 80

#include <iostream>#include <cmath>using namespace std;const float PI = 3.14159;float findCircum(float);float findArea(float);int main( ){ float radius = 10.0; float circum; float area; circum = findCircum(radius); area = findArea(radius); cout << “Area is “ << area << endl; cout << “Circumference is “ << circum << endl; return 0;}

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 81

// Computes the circumference of a circle with radius r

// Pre: r is defined and is > 0.

// PI is a constant.

// Post: returns circumference

float findCircum(float r)

{

return (2.0 * PI * r);

}

// Computes the area of a circle with radius r

// Pre: r is defined and is > 0.

// PI is a constant.

// Post: returns area

float findArea(float r)

{

return (PI * pow(r,2));

}

Figure 3.12 Functions findCircum and findArea

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 82

circum = findCircum(radius);

float findCircum(float r){ return (2.0 * PI * r);}

10

radius

10

r

62.8318

call findCircum62.8318

circum

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 83

Function Definition (Input Arguments with One Result)

• Syntax:

// function interface comment

ftype fname(formal-parameter-declaration-list)

{

local variable declarations

executable statements

}

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 84

Function Definition (Input Arguments with One Result)

• Example:// Finds the cube of its argument.// Pre: n is defined.int cube(int n){

return (n * n * n);}

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 85

Function Prototype (With Parameters)

• Form:

ftype fname(formal-parameter-type-list);

• Example:

int cube(int);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 86

Function Interface Comments

• Preconditions– conditions that should be true before function is

called– // Pre: r is defined

• Postconditions– conditions that will be true when function

completes execution– // Post: Returns circumference

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 87

Problem Inputs vs. Input Parameters

• Problem inputs– variables that receive data from program user– through execution of input statement

• Input parameters– receive data through execution of function call

statement– must be defined before function is called

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 88

Listing 3.14: Testing function testScale.cpp

// File testScale.cpp

// Tests function scale.

#include <iostream>

#include <cmath>

using namespace std;

// Function prototype

float scale(float, int);

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 89

int main(){ float num1; int num2;

// Get values for num1 and num2 cout << "Enter a real number: "; cin >> num1; cout << "Enter an integer: "; cin >> num2; // Call scale and display result. cout << "Result of call to function scale is " << scale(num1, num2) << endl; return 0;}

Listing 3.14: Testing function testScale.cpp (continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 90

// Multiplies its first argument by the power of 10

// specified by its second argument.

// Pre: x and n are defined and library cmath is

// included

float scale(float x, int n)

{

float scaleFactor; // local variable

scaleFactor = pow(10, n);

return (x * scaleFactor);

}

Listing 3.14: Testing function testScale.cpp (continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 91

float scale(float x, int n){ float scaleFactor; // local variable scaleFactor = pow(10, n); return (x * scaleFactor);}

cout << "Result of call to function scale is " << scale(num1, num2) << endl;

.

.

.

Formal parameters

Information flow

Actual arguments

Listing 3.14: Testing function testScale.cpp (continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 92

Argument/Parameter List Correspondence• Must have same number of actual

arguments and formal parameters• Order of arguments in the lists determines

correspondence• Each actual argument must be of a data type

that is compatible to the corresponding formal parameter

• The names of the actual arguments do not need to correspond to the formal parameters

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 93

Function Data Area

• Each time function is executed– an area of memory is allocated for storage of

the function’s data (formal parameters and local variables)

– it is created empty with each call to the function

• When the function terminates– the data area is lost

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 94

Data Areas After Call scale(num1, num2);

Function main Data

Area

Function Scale Data

Areanum1

num2

x

n

scaleFactor

2.5

-2

2.5

-2

?

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 95

Testing Functions Using Drivers

• Any function can be tested independently

• Test driver – defines values for the function’s arguments– calls the function– displays the value returned for verification

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 96

Scope of Names• Scope - where a particular meaning of a

name is visible or can be referenced• Local - can be referred to only within the

one function– applies to

• formal argument names• constants and variables declared within the function

• Global - can be referred to within all functions– useful for constants– must be used with care

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 97

Listing 3.15 Outline of program for studying scope of names

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 98

3.2 Library Functions

• Goals of software engineering– reliable code– accomplished by code reuse

• C++ promotes code reuse with predefined classes and functions in the standard library

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 99

C++ cmath Library

• Typical mathematical functions

e.g. sqrt, sin, cos, log

• Function use in an assignment statement

y = sqrt(x);

Function name

Function argument

Function call

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 100

Example: sqrt Function

Square root function

Function sqrt as a “black box”

X is 16.0 Result is 4.0

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 101

Listing 3.5 Illustration of the use of the C++ sqrt function

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 102

Listing 3.5 Illustration of the use of the C++ sqrt function (continued)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 103

Table 3.1 Some Mathematical Library Functions

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 104

Table 3.1 Some Mathematical Library Functions (continued)

105

Thank You

For

Your Attention!