Chapter 6: Modular Programming

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.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 6: Functions.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
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 06 (Part I) Functions and an Introduction to Recursion.
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.
1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 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.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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 Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
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.
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.
Principles of Programming & Software Engineering
Programming Logic and Design Seventh Edition
User-Written Functions
Completing the Problem-Solving Process
Chapter 6 Modular Programming Dr. J.-Y. Pan Dept. Comm. Eng.
Chapter 2 Assignment and Interactive Input
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Principles of Programming and Software Engineering
A Lecture for the c++ Course
Loop Structures.
Chapter 5 Function Basics
Chapter 5: Loops and Files.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 9 Scope, Lifetime, and More on Functions
Chapter 5 Function Basics
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.
Functions.
6 Chapter Functions.
Introduction to C++ Programming
CS150 Introduction to Computer Science 1
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Chapter 8 Functions.
Standard Version of Starting Out with C++, 4th Edition
Corresponds with Chapter 5
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

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

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

Listing 6.1 Function to compute sum and average

Listing 6.1 Function to compute sum and average (continued)

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

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

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

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

Figure 6.2 Data areas after execution of computeSumAve

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

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)

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

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

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

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

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

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

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

Listing 6.2 Functions main and test

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.

Listing 6.3 Testing function getFrac

Listing 6.3 Testing function getFrac (continued)

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

Listing 6.4 Function readFracProblem

Listing 6.5 Function to order three numbers

Listing 6.5 Function to order three numbers (continued)

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

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.

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

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)

Figure 6.4 Structure chart for general sum and average problem

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Listing 6.11 Testing function moneyToNumberString

Listing 6.11 Testing function moneyToNumberString (continued)

Listing 6.11 Testing function moneyToNumberString (continued)

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

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

Listing 6.12 Stub for function computeSum

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

Listing 6.13 A driver to test computeSum

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

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

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.

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

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

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.

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

Listing 6.14 Recursive function factorial

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