Modular Programming Chapter 6. 2 6.1 Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)

Slides:



Advertisements
Similar presentations
Chapter 6 Modular Programming J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Advertisements

Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
1 Lecture 10 Chapter 7 Functions Dale/Weems/Headington.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Chapter 6 Modular Programming Dr. J.-Y. Pan Dept. Comm. Eng. Nat. Chung Cheng Univ.
Functions:Passing Parameters by Value Programming.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
C++ for Engineers and Scientists Third Edition
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Basic Elements of C++ Chapter 2.
Chapter 6: Functions.
Programming Functions: Passing Parameters by Reference.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Functions g g Data Flow g Scope local global part 4 part 4.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
CPS120: Introduction to Computer Science Functions.
Functions Pass by reference, or Call by reference Passing addresses Use of & part 3.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Lecture 17: Modular Programming (cont) Debugging and Debuggers.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
User-Defined Functions (cont’d) - Reference Parameters.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Problem Solving and Program Design in C Chap. 6 Pointers and Modular Programming Chow-Sing Lin.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 7: User-Defined Functions II
Chapter 6: Modular Programming
Chapter 6 Modular Programming Dr. J.-Y. Pan Dept. Comm. Eng.
Basic Elements of C++.
Chapter 2 Assignment and Interactive Input
A Lecture for the c++ Course
Basic Elements of C++ Chapter 2.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CS150 Introduction to Computer Science 1
Chapter 8 Functions.
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Modular Programming Chapter 6

2 6.1 Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output) meanaverage(output)

3 computeSumAve.cpp // File: computeSumAve.cpp #include using namespace std; void computeSumAve (float, float, float&, float&); int main () { float x, y, sum, mean;

4 computeSumAve.cpp cout << "Enter 2 numbers: "; cin >> x >> y; computeSumAve (x, y, sum, mean); cout << " Sum is " << sum << endl; cout << " Average is " << mean << endl; return 0; }

5 computeSumAve.cpp // COMPUTES THE SUM AND AVERAGE OF NUM1 AND NUM2 // Pre: num1 and num2 are assigned values. // Post: The sum and average of num1 and num2 // are computed and returned as function outputs. void computesumave(float num1, float num2, float& sum, float& average) { sum = num1 + num2; average = sum / 2.0; }

6 Before Execution

7 After Execution

8 Call-by-Value and Call-by- Reference Parameters t Call by Value –Local function copy t Call by Reference (&) –Actual memory location

9 Call-by-Value and Call-by- Reference t & Call by Reference –Formal Argument in function heading –Argument list in function proto-type t Used to modify values in a function –Input –Input/Output –Output

10 Call by Value t Local copy of argument made at time of the function call t Local copy used in function t Modified local copy not actual value t When finished local copy destroyed t Actual value not changed

11 Call by Reference t Memory address of the actual argument is what is passed to the function t Because it is the address in memory of the actual argument you can modify its value t Data can flow into a function and out of the function

12 Protection and Usage of Value and Reference Parameters t Value arguments not changeable t Reference use could create a side effect t If one return value is enough use value arguments with a return t If more than one return is needed use reference arguments for the ones needing return values

13 Protection and Usage of Value and Reference Parameters t Typically use reference arguments in getData() type functions t Value arguments used with printing type functions t When a function must return more than one value a reference argument must be used t Avoid using reference arguments because of side effects (Large Projects)

14 Value and Reference Parameters t Expressions can be passed to functions –Always passed by value –Only variables can be passed by reference

Functions with Output and Input Parameters t Now examine functions that have only output or inout (input/output) parameters. t testGetFrac.cpp –Data items are entered at the keyboard t sort3Numbers.cpp –Demonstrate multiple calls to a function with inout parameters

16 testGetFrac.cpp // File: testGetFrac.cpp // Tests the fractions. #include using namespace std; getFrac(int&, int& ); int main() {

17 testGetFrac.cpp int num,denom; cout << "Enter a common fraction " << "as 2 integers separated by a slash: "; getFrac(num, denom); cout << "Fraction read is " << num << " / " << denom << endl; return 0; }

18 testGetFrac.cpp // Reads a fraction. // Pre: none // Post: numerator returns fraction numerator, // denominator returns fraction denominator void getFrac(int& numerator, int& denominator) { char slash; // Read the fraction cin >> numerator >> slash >> denominator; }

19 testGetFrac.cpp Program Output Enter a fraction as 2 integers separated by a slash : 3 / 4 The Fraction is : 3 / 4

20 sort3Numbers.cpp // FILE: sort3Numbers.cpp // READS THREE FLOATING POINT NUMBERS AND SORTS // THEM IN ASCENDING ORDER #include using namespace std; // SORTS A PAIR OF NUMBERS void order(float&, float&); int main () {

21 sort3Numbers.cpp // Local data... float num1, num2, num3; // Read and sort numbers. cout << "Enter 3 numbers to sort:"; cin >> num1 >> num2 >> num3; order (num1, num2); order (num1, num3); order (num2, num3);

22 sort3Numbers.cpp // Display results. cout << "The three numbers in order are:" << endl; cout << num1 << " " << num2 << " " << num3 << endl; return 0; }

23 sort3Numbers.cpp // SORTS A PAIR OF NUMBERS REPRESENTED BY x AND y void order(float& x, float& y) // Pre: x and y are assigned values. // Post: x is the smaller of the pair and y is // the larger. { // Local data... float temp;

24 sort3Numbers.cpp // Compare x and y and exchange values if not // properly ordered. if (x > y) { temp = x; x = y; y = temp; }

25 sort3Numbers.cpp Program Output Enter 3 numbers to be sorted separated by spaces: The three numbers in order are:

26 Sort3Numbers.cpp

Function Syntax & Arguments t Correspondence between actual and formal arguments is determined by position in their respective argument lists. These lists must be the same size. The names of corresponding actual and formal arguments may be different t Formal arguments and corresponding actual arguments should agree with respect to type

28 Function Syntax & Arguments t For reference arguments, an actual argument must be a variable. For value arguments, an actual argument may be a variable, a constant or an expression

Stepwise Design with Functions t Use functions as building blocks in design t Start small and add functions compiling as you go t Case study the sum and average problem t Classic Stepwise design steps

30 Stepwise Design with Functions t Problem statement t Problem analysis t Program design t Program implementation t Test and verification

31 Case Study Structure Chart ComputeSumComputeAvePrintSumAve

32 computeSumAve.cpp // File: computeSumAve.cpp // Computes and prints the sum and average of // a collection of data. // File: computeSumAveFunctions // Computes the sum and average of a collection // of data #include using namespace std;

33 computeSumAve.cpp // Functions used... // Computes sum of data float computeSum (int); // Computes average of data float computeAve (int, float); // Prints number of items, sum, and average void printSumAve (int, float, float);

34 computeSumAve.cpp int main() { // Local data... int numItems; float sum; float average; // Read the number of items to process. cout << "Enter the number of items to process:"; cin >> numItems;

35 computeSumAve.cpp // Compute the sum of the data. sum = computeSum(numItems); // Compute the average of the data. average = computeAve(numItems, sum); // Print the sum and the average. printSumAve(numItems, sum, average); return 0; }

36 computeSumAve.cpp // Insert definitions for functions computeSum, // computeAve, and printSumAve here. // Computes sum of data. // Pre: numItems is assigned a value. // Post: numItems data items read; their sum // is stored in sum. // Returns: Sum of all data items read if // numItems >= 1; otherwise, 0. float computeSum (int numItems) {

37 computeSumAve.cpp // Local data... float item; float sum; // Read each data item and accumulate it in // sum. sum = 0.0; for (int count = 0; count < numItems; count++) { cout << "Enter a number to be added: "; cin >> item; sum += item; } // end for

38 computeSumAve.cpp return sum; } // end computeSum // Computes average of data // Pre: numItems and sum are defined; numItems // must be greater than 0. // Post: If numItems is positive, the average is // computed as sum / numItems; // Returns: The average if numItems is positive; // otherwise, 0.

39 computeSumAve.cpp float computeAve (int numItems, float sum) { // Compute the average of the data. if (numItems < 1) { cout << "Invalid value for numItems = " << numItems << endl; cout << "Average not computed." << endl; return 0.0; } // end if return sum / numItems; } // end computeAve

40 computeSumAve.cpp // Prints number of items, sum, and average of // data // Pre: numItems, sum, and average are defined. // Post: Displays numItems, sum and average if // numItems > 0. void printSumAve (int numItems, float sum, float average) { // Display results if numItems is valid. if (numItems > 0) {

41 computeSumAve.cpp cout << "The number of items is " << numItems << endl; cout << "The sum of the data is " << sum << endl; cout << "The average of the data is " << average << endl; } else { cout << "Invalid number of items = " << numItems << endl;

42 computeSumAve.cpp cout << "Sum and average are not defined." << endl; cout << "No printing done. Execution terminated." << endl; } // end if } // end printSumAve

43 computeSumAve.cpp Program Output Enter the number of items to be processed: 3 Enter a number to be added: 5 Enter a number to be added: 6 Enter a number to be added: 17 The number of items is 3 The sum of the data is The average of the data is

Using Objects with Functions Two ways to use functions to process objects t Member function modifies the objects attributes –testString.remove (0, 5); t Pass object as a function argument –Passing string object in function doReplace.cpp

45 moneyToNumberTest.cpp // File: MoneyToNumberTest.cpp // Tests function moneyToNumberString #include using namespace std; // Function prototype void moneyToNumberString(string&);

46 moneyToNumberTest.cpp int main() { string mString; cout << "Enter a dollar amount with $ and commas: "; cin >> mString; moneyToNumberString(mString); cout << "The dollar amount as a number is " << mString << endl;

47 moneyToNumberTest.cpp return 0; } // Removes the $ and commas from a money string. // Pre: moneyString is defined and may contain // commas and begin with $ or -$. // Post: $ and all commas are removed from // moneyString. void moneyToNumberString (string& moneyString) {

48 moneyToNumberTest.cpp { // Local data... int posComma; // position of next comma // Remove $ from moneyString if (moneyString.at(0) == '$') moneyString.erase(0, 1); else if (moneyString.find("-$") == 0) moneyString.erase(1, 1); // Remove all commas posComma = moneyString.find(",");

49 moneyToNumberTest.cpp while (posComma >= 0 && posComma < moneyString.length()) { moneyString.erase(posComma, 1); posComma = moneyString.find(","); } } // end moneyToNumberString

Debugging and Testing a Program System t Top-Down testing and use of Stubs –Large projects –Stubs for all functions not finished (substitute for a specific function) just a heading without any details other than some type of message t Bottom-Up testing and use of Drivers –Driver used by developer to test full functionality of their function

51 Debugging and Testing a Program System t Debugging Tips for Program Systems –Carefully document each function parameter and local variable using comments as you write the code. Also describe the function’s purpose using comments. –Create a trace of execution by displaying the function name as you enter it. –Trace or display the values of all input and input/output parameters upon entry to a function. Check that these values make sense.

52 Debugging and Testing a Program System t Debugging Tips for Program Systems –Make sure that the function stub assigns a value to each output parameter. t Identifier Scope and Watch Window Variables t Black-Box Versus White-Box Testing

Common Programming Errors t Argument inconsistencies with Call by Reference Arguments –Side effects t Forgetting & t Argument type mismatch t Argument positional errors or missing arguments