Intro Programming in C++ Computer Science Dept Va Tech August, 2001 ©1995-2001 Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.

Slides:



Advertisements
Similar presentations
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Advertisements

Chapter 7: User-Defined Functions II
Parameter Passing Mechanisms Reference Parameters.
Functions CS 308 – Data Structures. Function Definition Define function header and function body Value-returning functions return-data-type function-name(parameter.
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.
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
Overview creating your own functions calling your own functions.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Basic Elements of C++ Chapter 2.
1 Chapter 7 Functions. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
6. Iteration Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Iteration pass (or iteration)-one.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Computer Arithmetic Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 1 Independent Representation.
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
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
Functions Why we use functions C library functions Creating our own functions.
9. Types Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Data Types data type:a collection of.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Parameter Passing Mechanisms Reference Parameters Read § §
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science Functions.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Parameter Passing Mechanisms Reference Parameters § §
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
7. Functions Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Scope of an Identifier scope(of.
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.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
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 © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
6. Iteration Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Iteration pass (or iteration)-one.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
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.
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.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Function Parameters and Overloading Version 1.0. Topics Call-by-value Call-by-reference Call-by-address Constant parameters Function overloading Default.
Chapter Topics The Basics of a C++ Program Data Types
Basic Elements of C++.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Basic Elements of C++ Chapter 2.
Chapter 9 Scope, Lifetime, and More on Functions
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
6 Chapter Functions.
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except for one special case discussed later -allocate a temporary memory location for each formal parameter (when function is called) -copy the value of the corresponding actual parameter into that location -called function has no access to the actual parameter, just to a copy of its value int FindMinimum(int A, int B) { if (A <= B) return A; else return B; }... int First = 15, Second = 42; int Least = FindMinimum(First, Second);... Created when call occurs and destroyed on return. Pass-by- Value Parameters

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 2 void SwapEm(int& A, int& B) { int TempInt; TempInt = A; A = B; B = TempInt; }... int First = 15, Second = 42; SwapEm(First, Second);... Pass-by-Reference Parameters Pass-by-Reference -put ampersand ( & ) after formal parameter type in prototype and definition -forces the corresponding actual and formal parameters to refer to the same memory location; that is, the formal parameter is then a synonym or alias for the actual parameter -called function may modify the value of the actual parameter

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 3 Pass-by-Constant-Reference -precede formal parameter type with keyword const, follow it with an ampersand ( & ) -forces the corresponding actual and formal parameters to refer to the same primary memory location; just as in pass-by-reference -but, the called function is not allowed to modify the value of the parameter; the compiler flags such a statement as an error int AddEm(const int& A, const int& B) { int Sum; Sum = A + B; return Sum; }... int First = 15, Second = 42, Third; Third = AddEm(First, Second);... Pass-by-Constant-Reference Parameters

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 4 Pass-by-Reference – use only if the design of the called function requires that it be able to modify the value of the parameter Pass-by-Constant-Reference – use if the called function has no need to modify the value of the parameter, but the parameter is very large (e.g., a string or a structure or an array, as discussed later) – use as a safety net to guarantee that the called function cannot be written in a way that would modify the value passed in † Pass-by-Value – use in all cases where none of the reasons given above apply – pass-by-value is safer than pass-by-reference † Note that if a parameter is passed by value, the called function may make changes to that value as the formal parameter is used within the function body. Passing by constant reference guarantees that even that sort of internal modification cannot occur. Choosing a Parameter Passing Mechanism

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 5 double CalcForce(int Weight, int Height){... } void getRGB(int& Red, int& Green, int& Blue){... } With pass by value, the actual parameter can be an expression (or a variable or a constant): With pass by reference and pass by constant reference, the actual parameter must be an l-value; that is, something to which a value can be assigned. That rules out expressions and constants. Parameter Restrictions F = CalcForce(mass * g, h);

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 6... int main( ) { // 1 const int W = 100; // 2 int X = 10, Y = 20, Z = 30; // 3 void Mix(int P, int& Z); // 4 Mix ( X, Y ); // 5 cout << W << X << Y << Z << endl; // 6 Mix ( Z, X ); // 7 cout << W << X << Y << Z << endl; // 8 return 0; // 9 } void Mix (int P, int& Z ) { // 10 int Y = 0, W = 0; // 11 Y = P; // 12 W = Z; // 13 Z = Z + 10; // 14 cout << P << W << Y << Z << endl; // 15 } Output Memory space for main() : Memory space for Mix() : P Z Y W W X Y Z Parameter Communication Trace

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 7 ///////////////////////////////////////////////////// isLeapYear() // Determines whether a given year is a leap year. // // Parameters: // Year year to be tested // // Returns: true if Year is a leap year, false otherwise // // Pre: Year has been initialized // Post: specified value has been returned // // Called by: buildCalendar() // Calls: none // bool isLeapYear (int Year) { return ( ( Year % 400 == 0 ) || ( ( Year % 4 == 0 ) && ( Year % 100 != 0 ) ) ); } // end isLeapYear Function Header Documentation

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 8 If a function needs to communicate just one value to the caller you may accomplish that in either of two ways: void versus Typed Functions The latter approach is generally preferred because it makes the effect of the function call clearer. Remember that in C++ there is no indication in the function call of which actual parameters are passed by reference (and hence at risk of being modified) and which are passed by value or constant reference (and hence guaranteed not to be modified by the function call). -use a void function with a reference parameter for communication -use a typed function with an appropriate return statement

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 9 Example... could be invoked in the following manner: void SquareIt(double Value, double& Square) { Square = Value * Value; } cin >> xval; SquareIt(xval, xsquared);// call is a separate statement cout << setw(10) << setprecision(4) << xsquared; cin >> xval; xsquared = SquareIt(xval); // called as part of an expression cout << setw(10) << setprecision(4) << xsquared; //... or even as: cout << setw(10) << setprecision(4) << SquareIt(xval); double SquareIt(double Value) { double Square = Value * Value; return Square; }... could be invoked in the following manner:

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 10 Problem: Write a program to accept as input a number of sums of money less than $1000 represented as 2 integers separated by a space and to output both the numeric form and its alphabetic equivalent for each sum. e.g. Input of should produce as output: ONE HUNDRED THIRTY-TWO DOLLARS AND FORTY-FIVE CENTS Note: The input sequence is terminated by a sum whose dollar amount is negative Application of this program n Printing of Computerized Bank Checks

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 11 Input Stepwise Refinement read(dollars, cents) write(dollars, cents)ECHO print if dollars > 0 convert dollars into words write(‘DOLLARS’) if cents > 0 write(‘AND’) if cents > 0 convert cents into words write(‘CENTS’)

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 12 { cin >> dollars; while(dollars >= 0) { cin >> cents; cout << dollars << " " << cents; if(dollars == 0 && cents == 0) cout << " NIL"; else { if(dollars > 0) { convert dollars into words; cout << " DOLLARS"; if(cents > 0) cout << " AND"; } if(cents > 0) { convert cents into words; cout << " CENTS"; } cout << endl; cin >> dollars; }

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 13 dollars into words cents into words FUNCTION.... void convert(int x) The function calls will be Question: Why is x a value parameter here? To refine "convert“ { split x into its hundreds, tens, units digits if H > 0 convert1 H if T = 1 convert2 T (a number between 10 and 19) else { convert3 T convert4 U } Question: Can any of these 4 converts be combined? { Convert suggest a HTU

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 14 void main() { void convert(int); // PROTOTYPE convert(dollars); convert(cents); } void convert(int x) { void convert1(int); void convert2(int); void convert3(int); convert1(H); convert2(T); convert3(T); convert1(U); } } PROTOTYPES...

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 15 void convert(int value) H T U value = H = value / 100;1 T = ? U = value % 10;2

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 16 Placement of Prototypes int main() { … convert (dollars); … convert(cents); … return 0; } void convert (int value) { … calls to convert1, convert2, convert3 … } void convert1 (int units) { … } + definitions of convert2, convert3

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 17 Declared Globally void convert (int); void convert1 (int); void convert2 (int); void convert3 (int); int main() { … } Void convert (int value) { … } + 3 further definitions

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 18 Declared when needed void main () { void convert (int); // PROTOTYPE convert (dollars); … convert (cents); } void convert (int x) { void convert1(int); void convert2(int); void convert3(int); convert1(H); … convert2(T); … convert3(T); … convert1(U); }

Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 19 Using Functions for Readings (Writing) To read data from an input file, using two (reading) functions: #include using namespace std; void fread1(ifstream&, int, int); void fread2(ifstream&, float, string); int main() { … ifstream infile; … fread1(infile, int1, int2); … fread(infile, float1, string1); … infile.close(); return 0; }