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

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

Embed Size (px)

Citation preview

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

Lecture 9: Top-Down Design with Functions

COS120 Software Development Using C++ AUBG, COS dept

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

Basics of functions. General form of a function definition

Functions topics: prototype, call, definition Systems defined and user defined functions The minimal C++ function Functions with multiple arguments

Page 3: Lecture 9: 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 is being illustrated using structure charts.

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

4

Basics of functions:

“Properly designed functions permit to ignore how a job’s done. Knowing what is done is sufficient.”

B.Kernighan & D.Ritchie

Most important reasons to use functions:

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

2. Using functions results in reduced program size.

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

5

Basics of functions:

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

B.Kernighan & D.Ritchie

Usually functions are specified to be called many times.

You can see often a short function defined and called only once, just because it clarifies some piece of code.

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

6

Details on functions

Three important topics when dealing with functions:

        prototype (signature) statement        function call statement         function definition (includes function

head or function title followed by a function body – compound statement surrounded in curly braces)

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

7

Syntax: functions with no argument(s) and no return value

Prototype statement: void fname(void);

Call statement: fname( );

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

statements>}

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

8

Syntax: functions 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 9: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

9

Syntax: functions with argument(s) and return value

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

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

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

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

}

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

10

The minimal C/C++ function

Minimal C++ function in 3 versions: it does nothing and returns “almost” nothing.

dummy() { }

dummy() { return 0; }

void dummy(void) { }

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

11

Functions with multiple arguments

The accent:Formal parameter: variableFormal parameters declaration list: parameters, i.e. variables,

separated by comma

Actual argument: literal, variable, fun. call, expressionList of actual arguments: arguments, separated by comma.

Example: function to compute (return) the average of two integers on next slide

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

12

Function to return average of two integers

Prototype in two versions:

double ave(int num1, int num2);

double ave(int, int);

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

13

Function to return average of two integers

Function definition in two versions:

// 1st versiondouble ave(int num1, int num2){ double result; result = (num1 + num2) / 2.; return result;}

OR

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

14

Function to return average of two integers

Function definition in two versions:

OR

// 2nd versiondouble ave(int num1, int num2){ return (num1 + num2) / 2.;}

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

15

Function to return average of two integers

Function definition in two versions:double ave(int num1, int num2) // 1st version { double result; result = (num1 + num2) / 2.; return result;}

ORdouble ave(int num1, int num2) // 2nd version{ return (num1 + num2) / 2.;}

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

16

Function to return average of two integers

Function call in variety of versions: Actual arguments: two literals

// value returned from ave directly displayed cout << endl << ave(30, 40);

// value returned from ave assigned to variable for use

double res; res = ave(50, 60); cout<<‘\n’<<“Average value is = “<< res;

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

17

Function to return average of two integers

Function call in variety of versions: Actual arguments: two variables initialized// value returned from ave directly displayed int a=60, b=40; cout << endl << ave(a, b);

// value returned from ave assigned to variable for use

double res; int a=650, b=420; res = ave(a, b); cout << ‘\n’ << “Average value is = “ << res;

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

18

Function to return average of two integers

Function call in variety of versions: Actual arguments: two variables loaded at runtime// value returned from ave directly displayed int a, b; cout <<“\nEnter 2 integers:”; cin >> a >> b; cout << endl << ave(a, b);

// value returned from ave assigned to variable for use

double res; int a, b; cout <<“\nEnter data:”; cin >> a >> b; res = ave(a, b); cout << ‘\n’ << “Average value is = “ << res;

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

19

Task to train functions

Create and test a function to return average of three integers

Create and test a function to return average of five integers

Create and test a function to return average of seven integers– Solution as a single function with 7 parameters– Solution based on a function with 2 only parameters – Reuse

functions ave2(p1,p2) and ave5(p1,p2,p3,p4,p5)

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

Attention: Next slide of high importanceRead carefully, think, understand

&

Do not forget what is written!!!

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

21

The Moral on function calling statement

If a function does not return a value, it’s called in the following context as a statement:

<fname>( <optional list of arguments> );

DrawHouse( );NumInBox(35.68);

If a function does return a value, it’s called in two other contexts: – As an operand of cout statement to display the value returned

cout << endl << ave(30,50);– As on operand in the right side of assignment statement

res = ave(60,70)*5 + pol/ave(56,88);

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

22

Function to return average of two integers

Function call in variety of versions:Actual arguments:

– Literal and variable– ave(30, x);– Expression composed of literal and variables– ave(x+y, b-4);– Run-time library function calls– ave(int(sqrt(6+p)),(int)exp(var));

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

23

Previous lecture reminder

Title:

Top-Down Design Using Functions

Source: Friedman/Koffman, Chapter 03

Have a quick look at next approx 60 slides to refresh your knowledge on functions

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

Top-Down Design with Functions and Classes

Chapter 3

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

25

3.2 Library Functions

– Goal of Structured Programming• Error free code

– Reusability• Don’t reinvent the wheel

– C ++ provides collection of functions

– Organized in Libraries• Library examples Table 3.1

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

26

C++ Math Library

– Functions in the Math library• sqrt cos sinpow

• Examples Table 3.1

– Function use in Assignmentsy = sqrt(x);

sqrt is function name

x is function argument

– Activated by a “function call”

– Result of execution is assigned to variable y

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

27

C++ Math Library (cont)

Function sqrt as a “black box”

Square rootcomputation

X is 16.0 Result is 4.0

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

28

C++ Library Functions

– We can effectively utilize existing functions by learning to read function prototypes with the preconditions and postconditions.

– Example prototype (or signature) double sqrt(double x); // PRE: x >= 0.0 // POST: Returns the square root of x.

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

29

Preconditions and Postconditions

– Comments that represents a contract between the implementor of a function and the user (client) of that function.

– We'll look at two such comments:• Precondition: What the function requires.• Postcondition: What the function will do if

the precondition is met.

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

30

Preconditions and Postconditions

– The preconditions are the circumstances that must be true before the function can successfully fulfill the promised postconditions.

– Example (Precondition abbreviates to PRE:double sqrt(double x);

// PRE: x >= 0

// POST: Returns square root of argument X

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

31

SquareRoot.cpp

// File: squareRoot.cpp// Performs three square root computations

#include <cmath> // sqrt function#include <iostream> // i/o functionsusing namespace std;

int main(){ float first; float second; float answer;

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

32

SquareRoot.cpp

// Get first number and display its square root. cout << "Enter the first number: "; cin >> first; answer = sqrt(first); cout << "The square root of the first

number is " << answer << endl;

// Get second number and display its square root. cout << "Enter the second number: "; cin >> second; answer = sqrt(second); cout << "The square root of the second

number is " << answer << endl;

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

33

SquareRoot.cpp

// Display the square root of the sum of first// and second.

answer = sqrt(first + second); cout << "The square root of the sum of

both numbers is " << answer << endl;

return 0;}

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

34

SquareRoot.cpp

Program Output

Enter the first number: 9The square root of the first number is 3Enter the second number: 16The square root of the second number is 4The square root of the sum of both numbers is 5

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

35

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 36: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

36

How to continue?

Next 35 slides (37-70) contain general purpose info on functions already discussed in previous two lectures

You may read them as a refreshing reminder OR

You may skip them jumping to slide titled “3.7 Extending C++ through Classes”

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

37

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 38: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

38

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 39: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

39

StickFigure.cpp

int main(){// Draw a circle. drawCircle();

// Draw a triangle. drawTriangle();

// Draw intersecting lines. drawIntersect();

return 0;}

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

40

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 41: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

41

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 42: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

42

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 43: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

43

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 44: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

44

Function Definition

void drawTriangle()

{

// Draw a triangle.

drawIntersect();

drawBase();

}

function header

function body

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

45

StickFigure.cpp

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

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

46

StickFigure.cpp

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

endl; cout << " " << symbol << " " << symbol <<

endl;}

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

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

47

StickFigure.cpp

// Draws intersecting lines

void drawIntersect(){ cout << " / \\ " << endl; cout << " / \\ " << endl; cout << " / \\" << endl;}

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

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

48

Order of Execution

int main()

{

drawCircle();

drawTriangle();

drawIntersect();

return 0;

}

void drawCircle()

{

cout << “ * “ << endl;

cout << “ * * “ << endl;

cout << “ * * “ << endl;

}

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

49

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 50: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

50

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 51: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

51

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 52: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

52

Instruct.cpp

// DISPLAYS INSTRUCTIONS TO 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 thesame units squared." << endl;}

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

53

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 54: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

54

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 55: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

55

Function Call

Form: fname(actual arg list);

Example: scale(3.0, z);

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

56

Function Return

Functions must return a value unless declared as void

Form: return expression;

Example: return x * y;

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

57

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 58: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

58

Function Prototype

Form: type fname (formal arg type list);

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

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

59

TestScale.cpp

// File testScale.cpp// Tests function scale. #include <iostream>#include <cmath>

using namespace std;

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

int main(){

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

60

TestScale.cpp

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

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

61

TestScale.cpp

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

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

62

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 63: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

63

Argument / Parameter List Correspondence

float scale(float x, int n)

{float scaleFactor;

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

}

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

64

Argument / Parameter List Correspondence

Function call scale (x + 2.0, y);

Actual Argument Formal Parameter

x + 2.0 x

y y

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

65

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 66: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

66

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 67: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

67

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 68: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

68

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 69: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

69

Scope of Names

Positional correspondence Type consistent is key because of positional

correspondence– Argument types– Return types

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

70

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 71: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

71

3.7 Extending C++ through Classes

– Discuss classes• String class part of compiler

– #include <string>

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

72

String Class

Declaring string objects Reading & Displaying strings Assignment & Concatenation Operator Overloading Dot Notation Member Functions Object Assignments

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

73

Declaring string Objects

A number of ways to declare

string firstName, lastName;

string wholeName;

string greeting = “Hello “;

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

74

Reading & Displaying string Objects

Use extraction operator >> and the stream cin for input–cin >> firstName;

Use insertion operator << and the stream cout for output– cout << greeting << wholeName << endl;

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

75

Reading & Displaying string Objects

getline(cin, lastName, ‘\n’);

reads all characters typed in from the keyboard up to the new line into the string object

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

76

Reading & Displaying string Objects

Other valid calls:

getline (cin, lastName);

getline (cin, lastName, ‘ ’);

getline (cin, lastName, ‘\t’);

getline (cin, lastName, ‘e’);

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

77

StringOperations.cpp

// ILLUSTRATES STRING OPERATIONS#include <iostream>#include <string>using namespace std;

int main (){

string firstName, lastName; string wholeName; string greeting = "Hello ";

cout << "Enter your first name: "; cin >> firstName;

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

78

StringOperations.cpp

cout << "Enter your last name: "; cin >> lastName;

// Join names in whole name wholeName = firstName + " " +

lastName;

// Display results cout << greeting << wholeName << '!' << endl; cout << "You have " <<

(wholeName.length () - 1) << " letters in your name."

<< endl;

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

79

StringOperations.cpp

// Display initials cout << "Your initials are "

<< (firstName.at(0)) << (lastName.at(0)) <<

endl;return 0;

}

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

80

StringOperations.cpp

Program outputEnter your first name: Caryn

Enter your last name: Jackson

Hello Caryn Jackson!

You have 12 letters in your name.

Your initials are CJ

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

81

Assignment

Stores the first and last name– wholeName = firstName + “ “ + lastName;

Concatenation– + joins the two objects together

“ “ for string values not ‘ ‘

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

82

Operator Overloading

+ normally means addition but with strings it means concatenation

The + can take on many meanings– Operator Overloading– C++ can have multi meanings to 1 operator– >> and << are overloaded operators, see next slide– * / - == = all can be overloaded

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

83

Operator Overloading

<< originally means shift left >> originally means shift right Here are more details on SHIFT operators:

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

84

Dot Notation

Dot notation used to call an objects member functions

wholeName.length();– Applies member function length to string object

wholeName– Function returns the objects length– Table 3.3 lists some additional functions

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

85

Header Files and Implementation Files

Header file (.h)– File containing information that C++ needs to

compile a program that accesses a user-defined class

Implementation file (.cpp)– File containing the C++ code for the operators

of a user defined class

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

86

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 params & actual args)

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

87

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 88: Lecture 9: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept

88

Exercise 9.1

Define a function and Build a program: to compute the volume of a pool

Design should include:– Function name– Return value data type– Number of parameters/arguments– Data type of parameters/arguments– Algorithm implementation

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

89

Exercise 9.2

Define a function and Build a program: To return the product of a real and an

integer using the formula m*10n

Design should include:– Function name– Return value data type– Number of parameters/arguments– Data type of parameters/arguments– Algorithm implementation

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

90

Exercise 9.3

Define a function and Build a program: to solve the Finding dollar value of coins

problem

Design should include:– Function name– Return value data type– Number of parameters/arguments– Data type of parameters/arguments– Algorithm implementation

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

91

Exercise 9.4

Define a function and Build a program: to solve the Feet/Inches to Meters

conversion problem

Design should include:– Function name– Return value data type– Number of parameters/arguments– Data type of parameters/arguments– Algorithm implementation

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

92

Homework 2

Paper record to be presented before the end of next class

Tasks:– See .doc file.

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

93

reminder

Quiz #2

on

Skills in C++ Functions

will take place next lesson

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

94

Before lecture end

Lecture:

Top-Down Design using Functions

More to read:

Friedman/Koffman, Chapter 03

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

95

Thank You

For

Your Attention!