76
Top-Down Design with Functions and Classes By Dr. Awad Khalil Computer Science & Engineering Department

3.1 Building Programs from Existing Information

  • Upload
    tauret

  • View
    35

  • Download
    0

Embed Size (px)

DESCRIPTION

Top-Down Design with Functions and Classes By Dr. Awad Khalil Computer Science & Engineering Department. 3.1 Building Programs from Existing Information. Reuse of existing programs Develop program in stages Compile along the way Keep it small Comments to describe actions. Washers.cpp. - PowerPoint PPT Presentation

Citation preview

Page 1: 3.1 Building Programs from Existing Information

Top-Down Design with Functions and Classes

By Dr. Awad Khalil

Computer Science & Engineering Department

Page 2: 3.1 Building Programs from Existing Information

2

3.1 Building Programs from Existing Information

Reuse of existing programsDevelop program in stagesCompile along the wayKeep it smallComments to describe actions

Page 3: 3.1 Building Programs from Existing Information

3

Washers.cpp// File: washers.cpp// Computes the weight of a batch of flat// washers.

#include <iostream>using namespace std;

int main(){ const float PI = 3.14159; float holeDiameter; // input -

Page 4: 3.1 Building Programs from Existing Information

4

Washers.cpp float edgeDiameter; // input - diameter float thickness; // input - thickness float density; // input - density float quantity; // input - number float weight; // output - weight float holeRadius; // radius of hole

float edgeRadius; // radius of outer edge

float rimArea; // area of rim

float unitWeight; // weight of 1 washer

Page 5: 3.1 Building Programs from Existing Information

5

Washers.cppcout << "Inner diameter in centimeters:

"; cin >> holeDiameter; cout << "Outer diameter in centimeters: "; cin >> edgeDiameter; cout << "Thickness in centimeters: "; cin >> thickness;

cout << "Material density in grams per cubic centimeter: ";

cin >> density; cout << "Quantity in batch: "; cin >> quantity;

Page 6: 3.1 Building Programs from Existing Information

6

Washers.cpp // Compute the rim area. holeRadius = holeDiameter / 2.0; edgeRadius = edgeDiameter / 2.0; rimArea = PI * edgeRadius * edgeRadius - PI * holeRadius * holeRadius;

// Compute the weight of a flat washer. unitWeight = rimArea * thickness * density; // Compute the weigh weight = unitWeight * quantity;

Page 7: 3.1 Building Programs from Existing Information

7

Washers.cpp // Display the weight

cout << "The expected weight of the batch is " << weight;

cout << " grams." << endl;

return 0;}

Page 8: 3.1 Building Programs from Existing Information

8

Washers.cpp

Program OutputInner Diameter in centimeters: 1.2Outer Diameter in centimeters: 2.4Thickness in centimeters: 0.1Material density in grams per cubic centimeter: 7.87Quantity in batch: 1000The expected weight of the batch is 2670.23 grams

Page 9: 3.1 Building Programs from Existing Information

9

3.2 Library FunctionsGoal of Structured Programming

Error free codeReusability

Don’t reinvent the wheelC ++ provides collection of functionsOrganized in Libraries

Library examples Table 3.1

Page 10: 3.1 Building Programs from Existing Information

10

C++ Math Library Functions in the Math library

sqrt cos sin powExamples Table 3.1

Function use in Assignmentsy = sqrt (x);sqrt is function namex is function argument

Activated by a “function call” Result of execution is assigned to variable y

Page 11: 3.1 Building Programs from Existing Information

11

C++ Math Library (cont)

Function sqrt as a “black box”

Square rootcomputation

X is 16.0 Result is 4.0

Page 12: 3.1 Building Programs from Existing Information

12

C++ Library FunctionsWe 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 13: 3.1 Building Programs from Existing Information

13

Preconditions and PostconditionsComments 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 14: 3.1 Building Programs from Existing Information

14

Preconditions and PostconditionsThe 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 15: 3.1 Building Programs from Existing Information

15

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 16: 3.1 Building Programs from Existing Information

16

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 17: 3.1 Building Programs from Existing Information

17

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 18: 3.1 Building Programs from Existing Information

18

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 19: 3.1 Building Programs from Existing Information

19

3.3 Top-Down Design and Structure Charts

D raw aC irc le

D rawin te rsec t in 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

Detailedsubproblems

Level 0

Level 1

Level 2

Page 20: 3.1 Building Programs from Existing Information

20

3.4 Functions without ArgumentsFunctions used in Top-Down Designmain() is just a function

called by OSC++ program is a collection of Functions

top level function is called the main()lower level functions

User Defined or LibrariesExample StkFigMn.cpp

Page 21: 3.1 Building Programs from Existing Information

21

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 22: 3.1 Building Programs from Existing Information

22

StickFigure.cpp

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

// Draw a triangle. drawTriangle();

// Draw intersecting lines. drawIntersect();

return 0;}

Page 23: 3.1 Building Programs from Existing Information

23

Function CallsWe 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 24: 3.1 Building Programs from Existing Information

24

Function CallsThis 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 25: 3.1 Building Programs from Existing Information

25

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 26: 3.1 Building Programs from Existing Information

26

Function Definition General form of a function definition: type function-name ( optional argument-list )

{local-declarations - function

bodyexecutable-statements

} Example function definition:

void drawTriangle ()

Page 27: 3.1 Building Programs from Existing Information

27

Function Definition

void drawTriangle (){ // Draw a triangle. drawIntersect (); drawBase ();

}

function header

function body

Page 28: 3.1 Building Programs from Existing Information

28

StickFigure.cpp

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

Page 29: 3.1 Building Programs from Existing Information

29

StickFigure.cpp

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

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

endl;}

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

Page 30: 3.1 Building Programs from Existing Information

30

StickFigure.cpp

// Draws intersecting lines

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

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

Page 31: 3.1 Building Programs from Existing Information

31

Order of Execution

int main(){ drawCircle(); drawTriangle(); drawIntersect(); return 0;}

void drawCircle(){ cout << “ * “ <<

endl; cout << “ * * “ <<

endl; cout << “ * * “ <<

endl;}

Page 32: 3.1 Building Programs from Existing Information

32

Function AdvantagesProgram team on large projectSimplify tasksEach Function is a separate unitTop-down approachProcedural abstraction Information hidingReuse (drawTriangle)

Page 33: 3.1 Building Programs from Existing Information

33

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 34: 3.1 Building Programs from Existing Information

34

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 35: 3.1 Building Programs from Existing Information

35

Instruct.cpp

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

int instruct (){

cout << "This program computes the area and " <<

endl;cout << "circumference of a circle. " <<

endl << endl;

cout << "To use this program, enter the radius of the " <<

endl; cout << "circle after the prompt" << endl;

Page 36: 3.1 Building Programs from Existing Information

36

Instruct.cpp

cout << "Enter the circle radius: " << endl << endl;

cout << "The circumference will be computed in the same ” << endl;

cout << "units of measurement as the radius. The area "

<< endl;cout << "will be computed in the same units

squared." << endl << endl;}

Page 37: 3.1 Building Programs from Existing Information

37

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 38: 3.1 Building Programs from Existing Information

38

3.5 Functions with Input Arguments

Functions used like building blocksBuild systems one functions at a time

Stereo ComponentsUse function return values and arguments

to communicate between functionsDiscuss AreaMain.cpp

Flow of arguments and returns

Page 39: 3.1 Building Programs from Existing Information

39

Function Call

Form: fname (actual arg list);

Example: scale (3.0, z);

Page 40: 3.1 Building Programs from Existing Information

40

Function Return

Functions must return a value unless declared as void

Form: return expression;

Example: return x * y;

Page 41: 3.1 Building Programs from Existing Information

41

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 42: 3.1 Building Programs from Existing Information

42

Function Prototype

Form: type fname (formal arg type list);

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

Page 43: 3.1 Building Programs from Existing Information

43

TestScale.cpp

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

using namespace std;

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

int main(){

Page 44: 3.1 Building Programs from Existing Information

44

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 45: 3.1 Building Programs from Existing Information

45

TestScale.cpp

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

Page 46: 3.1 Building Programs from Existing Information

46

Argument / Parameter List Correspondence

Functions can have more than 1 argCorrespondence between Actual &

Formal argumentsFunction call scale (3.0, z);Actual Argument Formal Argument

3.0 x z n

Page 47: 3.1 Building Programs from Existing Information

47

Argument / Parameter List Correspondence

float scale(float x, int n){

float scaleFactor;scaleFactor = pow(10, n);

return (x * scaleFactor);

}

Page 48: 3.1 Building Programs from Existing Information

48

Argument / Parameter List Correspondence

Function call scale (x + 2.0, y);

Actual Argument Formal Argument

x + 2.0 x y y

Page 49: 3.1 Building Programs from Existing Information

49

Argument / Parameter List Correspondence

Function call scale (y, x);

Actual Argument Formal Argument y x x y

Watch for type matches in formal and actual arguments

Page 50: 3.1 Building Programs from Existing Information

50

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 51: 3.1 Building Programs from Existing Information

51

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 52: 3.1 Building Programs from Existing Information

52

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

scopeCall anywhere in program

Functions declared globally

Page 53: 3.1 Building Programs from Existing Information

53

Scope of Names

Positional correspondence Type consistent is key because of positional

correspondenceArgument typesReturn types

Page 54: 3.1 Building Programs from Existing Information

54

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 55: 3.1 Building Programs from Existing Information

55

void one (ont anArg, double second); // prototype 1int funTwo (int one, char anArg); // prototype 2//const int MAX = 950;const int limit = 200;//int main (){

int localVar. . . . . . . . .

} // end main//void one(int anArg, double second} // header one{

int oneLocal; // local variable …………….} // end one//int funTwo (int one, char anArg) // header

funTwo{

int localVar; // local variable…………….

} // end funTwo

Page 56: 3.1 Building Programs from Existing Information

56

3.7 Extending C++ through Classes

Discuss two classesString class part of compilerMoney class is a user defined class

#include <string>#include “money.h”

Page 57: 3.1 Building Programs from Existing Information

57

String Class

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

Page 58: 3.1 Building Programs from Existing Information

58

Declaring string Objects

A number of ways to declare

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

Page 59: 3.1 Building Programs from Existing Information

59

Reading & Displaying string Objects Use extraction operator >> and the stream

cin for inputcin >> firstName;

Use insertion operator << and the stream cout for outputcout << greeting << wholeName <<

endl;

Page 60: 3.1 Building Programs from Existing Information

60

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 61: 3.1 Building Programs from Existing Information

61

StringOperations.cpp

// FILE: 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 62: 3.1 Building Programs from Existing Information

62

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 63: 3.1 Building Programs from Existing Information

63

StringOperations.cpp

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

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

<< endl;return 0;

}

Page 64: 3.1 Building Programs from Existing Information

64

StringOperations.cpp

Program outputEnter your first name: CarynEnter your last name: Jackson

Hello Caryn Jackson!You have 12 letters in your name.Your initials are CJ

Page 65: 3.1 Building Programs from Existing Information

65

Assignment

Stores the first and last namewholeName = firstName + “ “ +

lastName; Concatenation

+ joins the two objects together “ “ for string values not ‘ ‘

Page 66: 3.1 Building Programs from Existing Information

66

Operator Overloading + normally means addition but with strings

it means concatenation The + can take on many meanings

Operator OverloadingC++ can have multi meanings to 1

operator>> & << are overloaded operators* / - == = all can be overloaded

Page 67: 3.1 Building Programs from Existing Information

67

Dot Notation

Dot notation used to call an objects member functions

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

object wholeNameFunction returns the objects lengthTable 3.3 lists some additional functions

Page 68: 3.1 Building Programs from Existing Information

68

Money Class

Process money objects Two attributes

dollarscents

Why do this ?? Why not float ??

Page 69: 3.1 Building Programs from Existing Information

69

Money Class

Allocate a money objectmoney creditLimit = 5000.00;

Assignments taxAmount = salePrice *

taxPercent/100.0; finalCost = salePrice + taxAmount;

Page 70: 3.1 Building Programs from Existing Information

70

MoneyDemo.cpp

// FILE: MoneyDemo.cpp// ILLUSTRATES MONEY OPERATIONS

#include <iostream>#include "money.h" using namespace std;

int main (){

// Local declarations const float taxPercent = 6.25; money creditLimit = 5000.00;

Page 71: 3.1 Building Programs from Existing Information

71

MoneyDemo.cpp

money salePrice; money taxAmount; money finalCost; cout << "Enter item price: ";cin >> salePrice;

// Compute tax amount taxAmount = salePrice * taxPercent / 100.0;

// Compute final cost finalCost = salePrice + taxAmount;

Page 72: 3.1 Building Programs from Existing Information

72

MoneyDemo.cpp

// Display sales receipt cout << "Sales receipt" << endl; cout << "Price " << salePrice << endl; cout << "Tax " << taxAmount << endl; cout << "Paid " << finalCost << endl <<

endl; // Compute new credit limit

cout << "Your initial credit limit is " << creditLimit << endl;

creditLimit = creditLimit - finalCost; cout << "Your new credit limit is " <<

creditLimit << endl;return 0;

}

Page 73: 3.1 Building Programs from Existing Information

73

MoneyDemo.cpp

Program outputEnter item price: 345.77Sales ReceiptPrice $345.77Tax $21.61Paid $367.38

Your initial credit limit is $5,000.00Your new credit limit is $4,632.62

Page 74: 3.1 Building Programs from Existing Information

74

Header 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 75: 3.1 Building Programs from Existing Information

75

3.8 Common Programming Errors

Semicolon in Function Prototype (Declaration) Inconsistencies in Number of Arguments

Too few arguments in a callToo many arguments in a callIncorrect number of arguments in callExtra argument in call

Argument MismatchCorrect position (formal & actual params)

Page 76: 3.1 Building Programs from Existing Information

76

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