Cosc175/module.ppt1 Introduction to Modularity Function/procedures void/value-returning Arguments/parameters Formal arguments/actual arguments Pass by.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Functions, Interfaces, Parameters 8.1 – 8.2. include using namespace std; int main ( ) { int cal, fatGrams, fatCal; float fatPercent; cout
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: User-Defined Functions I
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Chapter 6: User-Defined Functions I
Chapter 6: Functions.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Functions g g Data Flow g Scope local global part 4 part 4.
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
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
First Steps in Modularization Simple Program Design Third Edition A Step-by-Step Approach 8.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
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 Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
FUNCTIONS (a) Value returning e.g. int main() ….…. return 0; (b) Void (returning) no return statements example To print this message **** ** Welcome.
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
First Steps in Modularization. Simple Program Design, Fourth Edition Chapter 8 2 Objectives In this chapter you will be able to: Introduce modularization.
First Steps in Modularization. Simple Program Design, Fourth Edition Chapter 8 2 Objectives In this chapter you will be able to: Introduce modularization.
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.
First Steps in Modularization. Simple Program Design, Fourth Edition Chapter 8 2 Objectives In this chapter you will be able to: Introduce modularization.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
Motivation Complexity of programming problem  more difficult to consider the solution as a whole  clue: dividing the problem into small parts (module)
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
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.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
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.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
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.
CHAPTER 8 Scope, Lifetime, and More on Functions.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 Functions Part 1 Prototypes Arguments Overloading Return values.
Chapter 6: User-Defined Functions I
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Chapter 7: User-Defined Functions II
User-Defined Functions
Chapter 6: User-Defined Functions I
Fundamental Programming
Presentation transcript:

cosc175/module.ppt1 Introduction to Modularity Function/procedures void/value-returning Arguments/parameters Formal arguments/actual arguments Pass by value/pass by reference Scope: global/local/name precedence

cosc175/module.ppt2 Modularity Most programs so far have been simple - less than one page in length In reality, most problems are not so simple top-down design - identify first the major tasks and further subtasks within them Modularity – breaking a program into subprograms

cosc175/module.ppt3 Module section of an algorithm which is dedicated to a single function 1.performs one single function 2.single entry, single exit 3.short enough to be easily read and modified 4.long enough to perform function

cosc175/module.ppt4 Modules all tasks can be subdivided and further subdivided into subtasks goal => can easily construct pseudocode for each subtask each module constructed and tested as unit Black Box Stubbing in (write dummy modules) –Always have something working

cosc175/module.ppt5 good names help Begin with Verb! Use several short words –PrintPageHeadings –CalcSalesTax –ValidateInputDate

cosc175/module.ppt6 Mainline or driver call subtasks should show the main processing functions, the order they should be performed easy to read manageable length Should include a loop!

cosc175/module.ppt7 Calling a subprogram/module int main() { …//line1 DoProc1(); //line2 ….//line3 } // end main //line4 //*************************** void DoProc1() { //line5 …..//line6 …..//line7 } // end DoProc1//line8 line2 Invokes or calls the subprogram Control is transferred to the subprogram: line5 The code in the subprogram is executed: line 6,7,8 At line8, control returns to statement following call, line 3 1,2,5,6,7,8,3,4

cosc175/module.ppt8 Hierarchy Chart shows who calls whom illustrates structure of the solution to a problem –i.e organization chart for a company shows top-down design, communication flow One block for each module Program name in first block, begin with verb

cosc175/module.ppt9 DoStuff DemoADemoBDemoC

cosc175/module.ppt10 Writing larger, more complex Programs 1.Define the problem –Input/Output –Processing => list of activities to be performed 2. Plan 1.Modularize => Hierarchy chart Group list of activities into modules 2. Construct code for main-line: Initial processing Loop processing //Contains calls to major processing modules(stubs) END Loop Final Processing 3.Construct code for each successive module in hierarchy chart 4.Desk-check each module in top-down fashion

cosc175/module.ppt11 advantages of well structured programs: –can easily be changed, updated and maintained –division into tasks makes them easy to understand –easy to construct –can test modules individually –easy to test and debug - easier to isolate errors can have each module print input and output –more reliable - fewer bugs

cosc175/module.ppt12 void functionValue-returning function returnCan return one or more values GetVals(x,y,z) returns one result return x * x nameBegins with a verb CalcSquare(..) Noun Square(..) C++void function void CalcSquare(..) Value returning function float Square(..) callstand-alone CalcSquare(..) Call is part of expression x = Square(..) miscMultipurposeUsually mathematical

cosc175/module.ppt13 void function example // prints lines of *’s where numLines specifies // how many lines to print void PrintLines( int numLines ) { int count; for (count = 1; count <=numlines; count++) cout << "***************" << endl; }

cosc175/module.ppt14 function as part of a program int main() { PrintLines(2); cout << " Welcome Home!“ << endl; PrintLines(4); return 0; } //*********************************************** // prints lines of *’s // numLines specifies how many lines to print void PrintLines( int numLines ) { int count; for (count = 1; count <=numlines; count++) cout << "***************" << endl; } //End PrintLines

cosc175/module.ppt15 Value returning Function examples //****************************** //this function returns the cube of x int Cube (int x) { return x * x * x; } //************************************************ //this function returns the maximum of 2 numbers int Max (int num1,int num2) { int max; if (num1 > num2 ) max = num1; else max = num2; return max; }

cosc175/module.ppt16 Functions in a program void Show Funcs() { int num1,num2; cout << “Enter two numbers” cin >> num1 >> num2; cout << "The max of " << num1 << " and << " num2 " is " << Max(num1,num2); cube = Cube(num1) cout << "The cube of " << num1 << " is " << Cube(num1); } //********************************************** //this function returns the cube of x int Cube (int x) { return x * x * x; } //************************************************ //this function returns the maximum of 2 numbers int Max (int num1,int num2) { int max; if (num1 > num2 ) max = num1; else max = num2; return max; }

cosc175/module.ppt17 When to use void versus value-returning When returning more than one value - use void when I/O is required - use void returning one Boolean value – value- returning returning one value to be used immediately in an expression – value-returning when in doubt - use void

cosc175/module.ppt18 arguments or parameters In function definition (formal arguments): void Name(type arg1, type arg2,…type argn) In call to function (actual arguments) Name(arg1,arg2,…argn) Arguments must match in number, order and data type but not name Can be 0,1, or many arguments

cosc175/module.ppt19 Formal and Actual Arguments Formal Argument In the definition –void PrintLines(int lines) Actual Argument In the call PrintLines(2); // could be constant: PrintLines(num); //could be variable: PrintLines(num+2) //could be Expression Note: actual parameter and formal arguments may have different names

cosc175/module.ppt20 Multiple parameters: matched by position each param must be declared: void PrintLines(int numLines,char whichChar); PrintLines(3,’$’);

cosc175/module.ppt21 Example Read three characters: Design a solution algorithm which will: prompt a terminal operator for three characters, accept those characters as input, sort them in ascending sequence and output them to the screen. The algorithm is to continue to accept characters until ‘XXX’ is entered.

cosc175/module.ppt22 InputProcessingOutput char11. Prompt for characters Sorted char1,char2,char3 char22. Accept three characters char33. Sort three characters 4.Output three characters

cosc175/module.ppt23 void ProcessThreeChars() { char char1,char2,char3; cout << “Enter three characters”; cin >> char1 >> char2 >>char3; while (!(char1 == ‘X’ && char2 == ‘X’ && char3 == ‘X’)) { if (char1 > char2 ) { temp = char1 char1 = char2 char2 = temp } if (char2 > char3) { temp = char2 char2 = char3 char3 = temp } if (char1 > char2) { temp = char1 char1 = char2 char2 = temp } cout << char1 << char2 << char3; cout << “Enter three characters”; cin >> char1 >>char2>>char3; }

cosc175/module.ppt24 void ProcessThreeChars() { char char1,char2,char3; cout << “Enter three characters”; cin >> char1 >> char2 >>char3; while (!(char1 == ‘X’ && char2 == ‘X’ && char3 == ‘X’)) { SortThreeCharacters(char1,char2,char3) cout << “Enter three characters”; cin >> char1 >>char2>>char3; }

cosc175/module.ppt25 void SortThreeCharacters(char& c1, char& c2,char& c3) { char temp; if (char1 > char2 ) { temp = char1 char1 = char2 char2 = temp } if (char2 > char3) { temp = char2 char2 = char3 char3 = temp } if (char1 > char2) { temp = char1 char1 = char2 char2 = temp }

cosc175/module.ppt26 two modules - main module - ReadThreeCharacters submodule - SortThreeCharacters after processing is complete, control is returned to main naming the module - passes control to the module

cosc175/module.ppt27 module invokes or calls subordinate modules –calling module –called module - return control to calling module upon completion of its task module may only call modules that are at the same level and immediately below it exception - library or utility modules (later) in general, no module should have more than seven modules subordinate to it

cosc175/module.ppt28 Parameters in, in out, out in - value parameters –pass by value –function receives a copy of the value in out, out - reference parameters –pass by reference –attach ampersand to data type, int& param –function receives the address of the actual parameter

cosc175/module.ppt29 Value Parameters void PrintLines(int numLines) –numLines is formal parameter void PrintLines(lineCount); –lineCount is actual parameter formal parameter receives a copy of the value of lineCount PrintLines cannot change lineCount # of actual params must match # of formal params types of actual params should match types of formal params –if not, implicit type coercion

cosc175/module.ppt30 Reference Parameters use & (C++ convention) function can change the value pass by reference location of parameter is passed only one copy of the value only variables can be passed as an actual parameter to a reference parameter

cosc175/module.ppt31 void SwapNums () { int x,y; x = 5; y = 10; cout << "Originally x = “ << x << " and y = “ << y; Swap(x,y); cout << "Now x = " << x << " and y = " << y; } void Swap(int u,int v) int temp; temp = u; u = v; v = temp; } Originally x = 5 and y = 10 Now x = 5 and y = 10

cosc175/module.ppt32 void SwapNums () { int x,y; x = 5; y = 10; cout << "Originally x = “ << x << " and y = “ << y; Swap(x,y); cout << "Now x = " << x << " and y = " << y; } void Swap(int& u,int& v) int temp; temp = u; u = v; v = temp; } Originally x = 5 and y = 10 Now x = 10 and y = 5

cosc175/module.ppt33 /// This program outputs an appropriate activity for a given temp. /#include void GetTemp( int& ); // Function prototypes void PrintActivity( int ); int main() { int temperature; // The outside temperature GetTemp(temperature); // Function call PrintActivity(temperature); // Function call return 0; } //****************************************************** // Prompt for, get, and echo current temperature void GetTemp( int& temp ) // Reference parameter { cout << "Enter the outside temperature:" << endl; cin >> temp; cout << "The current temperature is " << temp << endl; }

cosc175/module.ppt34 //****************************************************** // Given temperature, print appropriate activity void PrintActivity( int temp ) // Value parameter { cout << "The recommended activity is "; if (temp > 85) cout << "swimming." << endl; else if (temp > 70) cout << "tennis." << endl; else if (temp > 32) cout << "golf." << endl; else if (temp > 0) cout << "skiing." << endl; else cout << "dancing." << endl; }

cosc175/module.ppt35 Scope area of program where a variable is visible global - visible to all modules –declared in or above the main module local - visible only to the module in which it appears side effects - cross-communication of a module with other parts of a program

cosc175/module.ppt36 Local Variables each function is a block any function can declare variables within block accessible only within the block they are declared occupy space only when the function is executing when the function is invoked - local vars created when function is finished - local vars destroyed

cosc175/module.ppt37 global variables declared outside all functions int gamma; int main() { } void SomeFunc() {. } can be accessed from main or SomeFunc

cosc175/module.ppt38 It is possible to have identifiers with the same name both in the main program and the subprogram: name precedence - a local identifier in a module takes precedence over a global identifier with the same spelling in any reference the procedure makes to the identifier