Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: Modular Programming

Similar presentations


Presentation on theme: "Chapter 6: Modular Programming"— Presentation transcript:

1 Chapter 6: Modular Programming
Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman

2 6.1 Value and Reference Parameters
Functions can return no value type void return exactly one value return statement function type return more than one value reference parameters

3 Listing 6.1 Function to compute sum and average

4 Listing 6.1 Function to compute sum and average (continued)

5 Function computeSumAve
Two input parameters num1, num2 Two output parameters sum, average & indicates output parameters Function call computeSumAve(x, y, sum, mean);

6 Argument Correspondence
Actual Argument x y sum mean Corresponds to Formal Argument num1 (input) num2 (input) sum (output) average (output)

7 Call-by-Value and Call-by-Reference Parameters
& between type and identifier defines a parameter as output mode (pass by reference) actual memory location is passed no & in a parameter’s declaration identifies input mode (pass by value) copy of the value in the memory location is passed Compiler uses info in parameter declaration list to set up correct argument-passing mechanism

8 Figure 6.1 Data areas after call to computeSumAve (before execution)

9 Figure 6.2 Data areas after execution of computeSumAve

10 Notes on Call-by-Reference
Place the & only in the formal parameter list - not in the actual parameter list Place the & also in the prototype: void computeSumAve(float, float, float&, float&); Note that this is a void function

11 When to Use a Reference or a Value Parameter
If information is to be passed into a function and doesn’t have to be returned or passed out of the function, then the formal parameter representing that information should be a value parameter (input parameter)

12 When to Use a Reference or a Value Parameter
If information is to be returned to the calling function through a parameter, then the formal parameter representing that information must be a reference parameter (output parameter).

13 When to Use a Reference or a Value Parameter
If information is to be passed into a function, perhaps modified, and a new value returned, then the formal parameter representing that information must be a reference parameter (input/output parameter) Note: C++ does not distinguish between output parameters and input/output parameters

14 Program Style Formal parameter list often written on multiple lines to improve readability. Value parameters first, followed by reference parameters Comment each parameter to identify its use

15 Summary of Value Parameters
Value of corresponding actual argument is stored in the called function The function execution cannot change the actual argument value actual argument can be an expression, variable, or constant formal parameter type must be spcified in the formal parameter list Parameters are used to store the data passed to a function

16 Summary of Reference Parameters
Address of corresponding actual argument is stored in the called function The function execution can change the actual argument value Actual argument must be a variable only Formal parameter type must be followed by & in the formal parameter list Parameters are used to return outputs from the function or to change the value of a function argument

17 Argument/Parameter List Correspondence
Number: number of actual arguments used in function call must be the same as the number of formal parameters listed in the function header and prototype Order: Order of arguments in the lists determines correspondence

18 Argument/Parameter List Correspondence
Type: Each actual argument must be of a data type that can be assigned to the corresponding formal parameter with no unexpected loss of information For reference parameters, an actual argument must be a variable. For value parameters, an actual argument may be a variable, a constant, or an expression

19 Listing 6.2 Functions main and test

20 6.2 Functions with Output and Inout Parameters
Function getFrac reads a common fraction typed in by a user and returns the numerator and denominator through two type int output parameters.

21 Listing 6.3 Testing function getFrac

22 Listing 6.3 Testing function getFrac (continued)

23 Example Function readFracProblem reads a problem involving two common fractions. The function outputs would be the numerator and denominator of both fractions, and the operation (as a character) Function readFracProblem calls function getFrac twice

24 Listing 6.4 Function readFracProblem

25 Listing 6.5 Function to order three numbers

26 Listing 6.5 Function to order three numbers (continued)

27 6.3 Stepwise Design with Functions
Arguments are used to pass information to and from functions Use functions to encode complex tasks

28 Case Study: General Sum and Average Problem
You have been asked to accumulate a sum and to average a list of data values using functions. Because these tasks surface in many problems, design a general set of functions you can reuse in other programs.

29 Case Study: Analysis Data Requirements Formula Problem Input
int numItems the data items Problem Output float sum float average Formula Average = Sum of data / number of data items

30 Case Study: Design - Initial Algorithm
1. Read the number of items 2. Read the data items and compute the sum of the data (computeSum) 3. Compute the average of the data (computeAve) 4. Print the sum and average (printSumAve)

31 Figure 6.4 Structure chart for general sum and average problem

32 Case Study: Implementation
Convert data requirements into local declarations for function main. Declare all the variables appearing in the structure chart in the main function Use algorithm steps as comments in the main function Code each algorithm step

33 Case Study: Implementation
Data flow information indicates Name of each function Actual arguments Name of the main program variable that will hold the results of each function call

34 Listing 6.6 main function // File: computeSumAve.cpp
// Computes and prints the sum and average of a collection of data #include <iostream> using namespace std; // Functions used . . . // Computes sum of data float computeSum (int); // IN - number of data items // Computes average of data float computeAve (int, // IN - number of data items float); // IN - sum of data items // Prints number of items, sum, and average void printSumAve float, // IN - sum of the data float); // IN - average of the data

35 Listing 6.6 main function (continued)
int main( ) { int numItems; // input - number of items to be added float sum; // output - accumulated sum of the data float average; // output - average of data being processed // Read the number of items to process. cout << “Enter the number of itesm to process: “; cin >> numItems; // 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 Analysis for computeSum
Given the number of items to be processed as an input parameter (numItems) Responsible to reading and computing the sum of this number of values The sum is then returned

37 Function Interface for computeSum
Input Parameters int numItems Output Parameters none Function Return Value the sum (float) of the data items processed Local Data float item, float sum, int count

38 Design of computeSum: Initial Algorithm
1. Initialize sum to zero 2. For each value of count from 0, as long as count < numItems 2.1 Read in a data item 2.2 Add the data item to sum 3. Return sum

39 Listing 6.7 Function computeSum
// 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) // IN: number of data items { // Local data . . . float item; // input: contains current data item float sum; // output: used to accumulate sum of data // read in

40 Listing 6.7 Function computeSum (continued)
// 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 return sum; } // end computeSum

41 Analysis for computeAve
Function Interface Input Parameters int numItems float sum Output Parameters none Function Return Value the average of all the data (float)

42 Design of computeAve - Initial Algorithm
1. If the number of items is less than 1 1.1 display “invalid number of items” message 1.2 return a value of 0 2. Return the value of the sum divided by numItems

43 Listing 6.8 Function computeAve
// 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; float computeAve (int numItems, // IN: number of data items float sum; // IN: sum of data

44 Listing 6.8 Function computeAve (continued)
{ // Compute the average of the data. if (numItems < 1) // test for invalid input cout << “Invalid value for numItems = “ << numItems << endl; cout << “Average not computed.” << endl; return 0.0; // return for invalid input } return sum / numItems; } // end computeAve

45 Function Interface for printSumAve
Input Parameters int numItems float sum float average Output Parameters none

46 Design of printSumAve - Initial Algorithm
1. If the number of items is positive 1.1 Display the number of items and the sum and average of the data else 1.2 Display “invalid number of items” message

47 Listing 6.9 Function printSumAve
// 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, // IN: number of data items float sum, // IN: sum of the data float average) // IN: average of the data

48 Listing 6.9 Function printSumAve (continued)
{ // Display results is numItems is valid. if (numItems > 0) 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; cout << “Sum and average are not defined.“ << endl; cout << “No printing done. Execution terminated.” << endl; } // end if } // end printSumAve

49 Case Study: Testing Make sure
sum and average are displayed correctly when numItems is positive a meaningful diagnostic is displayed when numItems is zero or negative

50 Multiple Declarations of Identifiers in a Program
Identifiers sum and numItems declared in main and as formal parameters Each of these declarations has its own scope scope for each formal parameter is the function that declares it Could introduce different names in each function to avoid confusion, but same name throughout may be easier to read

51 Use of Functions for Relatively Simple Algorithm Steps
Want to encourage use of separate functions Helps keep details of steps separate and hidden Makes the program easier to debug, test, and modify at some future date May be able to reuse the function

52 Cohesive Functions Functions that perform a single operation are called functionally cohesive Single-purpose, highly cohesive functions are good programming practice helps keep function relatively compact easier to write, read, and debug

53 6.4 Using Objects with Functions
Two ways to use functions to process objects Use dot notation to apply member function - member function modifies the object’s attributes testString.remove (0, 5); Pass object as a function argument Passing string object in function doReplace.cpp

54 moneyToNumberString A single inout argument of type string
Function removes $ and commas

55 Listing 6.11 Testing function moneyToNumberString

56 Listing 6.11 Testing function moneyToNumberString (continued)

57 Listing 6.11 Testing function moneyToNumberString (continued)

58 6.5 Debugging and Testing a Program System
Keep each function to a manageable size errors less likely easier to read simplifies testing Two kinds of testing Top-down Bottom-up

59 Top-Down Testing and Stubs
Useful for 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

60 Listing 6.12 Stub for function computeSum

61 Bottom-Up Testing and Drivers
Unit testing tests each function individually Driver used by developer to test full functionality of their function contains only sufficient declarations and executable statements to test a specific function System integration tests combine functions for additional testing

62 Listing 6.13 A driver to test computeSum

63 Debugging Tips for Program Systems
Use comments to document each function parameter and local variable describe the function’s purpose Create a trace of execution by outputting the function name as the function is entered Trace (display) the values of all input and inout parameters upon function entry

64 Debugging Tips for Program Systems
Trace the values of all function outputs after returning from function. Verify. Make sure all inout and output parameters are declared as reference parameters (&), Make sure function stub assigns a value to each output parameter. Make sure function driver assigns a value to each input parameter

65 Identifier Scope and Watch Window Variables
A debugger can help trace values passed into and out of a function. The values are displayed in a Watch window based on each identifier’s scope.

66 Black-Box Testing Assumes the program tester has no information about the code inside the function or system. Tester’s job is to verify that the function or system meets specifications. for each function, ensure that postconditions are satisfied whenever its preconditions are met check for function crashing due to invalid input values check boundaries of system

67 White-Box Testing Tester has full knowledge of function code
Must ensure each section of code has been thoroughly tested. Check all possible paths Determine that for each test correct path is taken For loops, make sure correct number of iterations Check boundary values

68 6.6 Recursive Functions Recursive function calls itself, with different argument values for each call Must identify a stopping case - a situation that stops the recursion.

69 Template for a Recursive Function
1. If the stopping case is reached 1.1 Return a value for the stopping case Else 1.2 Return a value computed by calling the function again with different arguments

70 Listing 6.14 Recursive function factorial

71 6.7 Common Programming Errors
Parameter inconsistencies with call-by-reference parameters Forgetting to use & with call-by-reference parameters Warning messages from compiler should not be ignored


Download ppt "Chapter 6: Modular Programming"

Similar presentations


Ads by Google