Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 8: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept."— Presentation transcript:

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

2 2 Lecture Contents: t Top-Down Design and step-wise refinement with structure charts t Functions topics: prototype, call, definition t Functions with input argument(s) and no return value t Functions with input argument(s) and returning a single value as a result t The return statement t Library functions

3 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 4 Summary on functions Prototype statement: void fname(void); Call statement: fname( ); Function Definition: void fname(void) { }

5 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 6 Valid reasons to create a routine: t 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 t Avoid duplicate code –Usually functions are specified to be called many times.

7 7 Details on functions Three important topics when dealing with functions:  prototype (signature) statement  function call statement  function definition

8 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 9 General notation – function with no argument(s) Prototype: void fname(void); Call: fname(); Definition: void fname(void) { }

10 10 General notation – function with argument(s) and no return value Prototype: void fname( ); Call: fname( ); Definition: void fname( ) { }

11 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.6789 Output:input number to be displayed in a box composed of 5 lines: 1 st line: 11 stars*********** 2 nd line: star, 9 spaces, star* * 3 rd line: star, space, 7 digits, space, star* 35.6789 * 4 th line: star, 9 spaces, star* * 5 th line: 11 stars***********

12 12 Possible solutions t Spaghetti code version –No need to comment t Function with no parameter and no return value Function 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 13 Functions may get input data

14 14 Intro to functions with params t 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. t We need a tool to transfer the number to be displayed into the function. t 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 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: 1 st line: 11 stars*********** 2 nd line: star, 9 spaces, star* * 3 rd line: star, space, 7 digits mask, space, star* xxxxxxx * 4 th line: star, 9 spaces, star* * 5 th line: 11 stars***********

16 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 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 18 Example – to display a real number in a box Function prototype: void NumInBox(double num);

19 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 20 Example – full program on back page of the handout #include using namespace std; void NumInBox(double num);// user defined function’s prototype void 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 21 Functions may return data

22 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. t 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 23 General notation – function with argument(s) and return value Prototype: ftype fname( ); Call: fname( ); Definition: ftype fname( ) { return ( ); }

24 24 The return statement t Syntax: return; return( );

25 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(…) t See solution on next slide

26 26 Problem: the area of a circle double 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 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

28 Top-Down Design with Functions and Classes Chapter 3

29 29 3.3 Top-Down Design and Structure Charts Original Problem Detailed subproblem s Level 0 Level 1 Level 2

30 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 31 StickFigure.cpp // File: stickFigure.cpp // Draws a stick figure #include using namespace std; // Functions used... void drawCircle(); // Draws a circle void drawTriangle(); // Draws a triangle void drawIntersect(); // Draws intersecting lines void drawBase(); // Draws a horizontal line

32 32 StickFigure.cpp int main() { // Draw a circle. drawCircle(); // Draw a triangle. drawTriangle(); // Draw intersecting lines. drawIntersect(); return 0; }

33 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 34 Function Calls –This general form of a function call: function-name( ); –Example function call: drawCircle( ); –The function name is drawCircle –No arguments to the function

35 35 Function Prototype –This general form of a function prototype: type function-name( ); –Example function prototype: void skipThree( ); –Type int - float - char –Name –( ); –Descriptive comment

36 36 Function Definition –General form of a function definition: type function-name( ) { local-declarations- function body executable-statements } –Example function definition: void drawTriangle( )

37 37 Function Definition void drawTriangle() { // Draw a triangle. drawIntersect(); drawBase(); } function header function body

38 38 StickFigure.cpp // Draws a circle void drawCircle() { cout << " * " << endl; cout << " * *" << endl; } // end drawCircle

39 39 StickFigure.cpp void drawCircleChar(char symbol) { cout << " " << symbol << " " << endl; cout << " " << symbol << " " << symbol <<endl; } // Draws a triangle void drawTriangle() { drawIntersect(); drawBase(); }

40 40 StickFigure.cpp // Draws intersecting lines void drawIntersect() { cout << " / \\ " << endl; } // draws a horizontal line void drawBase() { cout << "-------" << endl; }

41 41 Order of Execution int main() { drawCircle(); drawTriangle(); drawIntersect(); return 0; } void drawCircle() { cout << “ * “ << endl; cout << “ * * “ << endl; }

42 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 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 44 Displaying User Instructions t We still have not covered passing in and out of a function t Following example shows displaying info –instruct(); function call in main

45 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 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 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 48 Function Call Form: fname( ); Example: scale(3.0, z);

49 49 Function Return t Functions must return a value unless declared as void Form: return ; Example: return x*y;

50 50 Function Definition Form: type fname( ) { function body } Example: float scale(float x, int n) { float scaleFactor; scaleFactor = pow(10, n); return (x * scaleFactor); }

51 51 Function Prototype Form: type fname( ); Example: float scale(float x, int n);

52 52 TestScale.cpp // Tests function scale. #include using namespace std; // Function prototype float scale(float, int);

53 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 54 TestScale.cpp float scale(float x, int n) { float scaleFactor; scaleFactor = pow(10, n); return (x * scaleFactor); }

55 55 Argument / Parameter List Correspondence –Functions can have more than 1 arg –Correspondence between Actual & Formal arguments Function call: scale (3.0, z); Actual ArgumentFormal Parameter 3.0x zn

56 56 Argument / Parameter List Correspondence float scale(float x, int n) { float scaleFactor; scaleFactor = pow(10, n); return (x * scaleFactor); }

57 57 Argument / Parameter List Correspondence Function call: scale(x + 2.0, y); Actual Argument Formal Parameter x + 2.0x y y

58 58 Argument / Parameter List Correspondence Function call: scale(y, x); Actual ArgumentFormal Parameter yx xy Watch for type matches in formal parameters and actual arguments

59 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 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 61 3.6 Scope of Names t Variable declared in a function has a local scope within the function t Same for variables declared in the main t Variable declared before main is global scope –Call anywhere in program t Functions declared globally

62 62 Scope of Names t Positional correspondence t Type consistent is key because of positional correspondence –Argument types –Return types

63 63 Scope of Names t Type of a value returned by a called function must be consistent with the type expected by the caller as identified in the prototype t Type of an actual argument in a function call must be consistent with the type of its corresponding formal argument

64 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 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 66 Exercise 8.1 Define a function and Build a program: to compute the area of a circle double FindArea(double rad);

67 67 Exercise 8.2 Define a function and Build a program: to compute the circumference of a circle double FindCircum(double rad);

68 68 Exercise 8.3 Define a function and Build a program: to compute the area of a square int FindSqArea(int side);

69 69 Exercise 8.4 Define a function and Build a program: to compute the perimeter of a square int FindSqPerim(int side);

70 70 Exercise 8.5 Define a function and Build a program: to solve the Miles-to-Kilometers conversion problem double ConvMilesToKms(double kms);

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

72 72 Library functions List of some Character Library Functions (#include ) 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 73 Before lecture end Lecture: Top-Down Design using Functions More to read: Friedman/Koffman, Chapter 03

74 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

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

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

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

78 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 78 drawCircleChar(‘*’); void drawCircle(char symbol) { cout << “ “ << symbol << endl; cout << “ “ << symbol << “ “ << symbol << endl; } // end drawCircle ‘*’ symbol

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

80 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 80 #include 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; }

81 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

82 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 findCircum 62.8318 circum

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

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

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

86 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

87 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

88 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 using namespace std; // Function prototype float scale(float, int);

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

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

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

92 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

93 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

94 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 Area num1 num2 x n scaleFac tor 2.5 -2 2.5 -2 ?

95 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

96 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

97 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 97 Listing 3.15 Outline of program for studying scope of names

98 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

99 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

100 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.0Result is 4.0

101 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 101 Listing 3.5 Illustration of the use of the C++ sqrt function

102 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 102 Listing 3.5 Illustration of the use of the C++ sqrt function (continued)

103 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 103 Table 3.1 Some Mathematical Library Functions

104 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 104 Table 3.1 Some Mathematical Library Functions (continued)

105 105 Thank You For Your Attention!


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

Similar presentations


Ads by Google