105
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

Embed Size (px)

Citation preview

Page 1: 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

Page 2: 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

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

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.

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

4

Summary on functions

Prototype statement: void fname(void);

Call statement: fname( );

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

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

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.

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

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.

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

7

Details on functions

Three important topics when dealing with functions:

        prototype (signature) statement

        function call statement

        function definition

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

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.

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

9

General notation – function with no argument(s)

Prototype: void fname(void);

Call: fname();

Definition: void fname(void){

<local declarations><executable statements>

}

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

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>

}

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

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 ***********

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

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";

}

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

13

Functions may get

input data

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

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.

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

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 ***********

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

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";

}

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

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";

}

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

18

Example – to display a real number in a box

Function prototype:

void NumInBox(double num);

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

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

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

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"; }

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

21

Functions may

return data

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

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.

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

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

}

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

24

The return statement

Syntax:

return;

return <expression>;

return(<expression>);

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

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

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

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;}

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

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

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

Top-Down Design with Functions and Classes

Chapter 3

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

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

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

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

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

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

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

32

StickFigure.cpp

int main(){

// Draw a circle.drawCircle();

// Draw a triangle.drawTriangle();

// Draw intersecting lines.drawIntersect();

return 0;}

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

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.

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

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

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

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

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

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

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

37

Function Definition

void drawTriangle()

{

// Draw a triangle.

drawIntersect();

drawBase();

}

function header

function body

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

38

StickFigure.cpp

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

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

39

StickFigure.cpp

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

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

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

40

StickFigure.cpp

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

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

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

41

Order of Execution

int main()

{

drawCircle();

drawTriangle();

drawIntersect();

return 0;

}

void drawCircle()

{

cout << “ * “ << endl;

cout << “ * * “ << endl;

cout << “ * * “ << endl;

}

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

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)

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

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

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

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

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

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;}

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

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.

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

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

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

48

Function Call

Form: fname(<actual arg list>);

Example: scale(3.0, z);

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

49

Function Return

Functions must return a value unless declared as void

Form: return <expression>;

Example: return x*y;

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

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

}

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

51

Function Prototype

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

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

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

52

TestScale.cpp

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

using namespace std;

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

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

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;}

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

54

TestScale.cpp

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

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

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

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

56

Argument / Parameter List Correspondence

float scale(float x, int n)

{

float scaleFactor;

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

scaleFactor);

}

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

57

Argument / Parameter List Correspondence

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

Actual Argument Formal Parameter

x + 2.0 x

y y

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

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

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

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

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

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.

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

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

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

62

Scope of Names

Positional correspondence Type consistent is key because of positional

correspondence– Argument types– Return types

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

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

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

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)

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

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

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

66

Exercise 8.1

Define a function and Build a program:

to compute the area of a circle

double FindArea(double rad);

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

67

Exercise 8.2

Define a function and Build a program:

to compute the circumference of a circle

double FindCircum(double rad);

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

68

Exercise 8.3

Define a function and Build a program:

to compute the area of a square

int FindSqArea(int side);

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

69

Exercise 8.4

Define a function and Build a program:

to compute the perimeter of a square

int FindSqPerim(int side);

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

70

Exercise 8.5

Define a function and Build a program:

to solve the Miles-to-Kilometers conversion problem

double ConvMilesToKms(double kms);

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

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

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

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

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

73

Before lecture end

Lecture:

Top-Down Design using Functions

More to read:

Friedman/Koffman, Chapter 03

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

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

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

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)

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

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

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

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(‘*’);

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

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

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

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;

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

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;}

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

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

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

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

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

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

}

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

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);}

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

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

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

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

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

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

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

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

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

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)

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

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)

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

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)

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

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

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

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

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

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

?

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

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

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

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

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

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

Listing 3.15 Outline of program for studying scope of names

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Table 3.1 Some Mathematical Library Functions

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

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

Table 3.1 Some Mathematical Library Functions (continued)

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

105

Thank You

For

Your Attention!