Jozef Goetz, 2015 1  2002 Prentice Hall. All rights reserved. Credits:  2011-2014 Pearson Education, Inc. All rights reserved.

Slides:



Advertisements
Similar presentations
 2006 Pearson Education, Inc. All rights reserved Functions.
Advertisements

Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2002 Prentice Hall. All rights reserved. 1 Chapter 6 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 6.14Recursion 6.15 Example.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Review for Midterm 2 Nested loops & Math class methods & User defined methods.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Chapter 7 Methods: A Deeper Look Visual C# 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
1 C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
 2002 Prentice Hall. All rights reserved. 1 Week 2: Methods Questions about last week’s revision –C#.NET –.NET Framework –sequence, selection, repetition.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
 2008 Pearson Education, Inc. All rights reserved Function Call Stack and Activation Records Data structure: collection of related data items.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
1 CS1120: Recursion. 2 What is Recursion? A method is said to be recursive if the method definition contains a call to itself A recursive method is a.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
1 Recursion Recursive method –Calls itself (directly or indirectly) through another method –Method knows how to solve only a base case –Method divides.
Jozef Goetz,  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
 2001 Prentice Hall, Inc. All rights reserved. 1 Introduction to C# Part II.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math -Class Methods 6.4.
C# Programming Methods.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
C++ Programming Lecture 12 Functions – Part IV
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Lecture 02 Dr. Eng. Ibrahim El-Nahry Methods. 2 Learning Objectives Class Definition includes both methods and data properties Method Definition and Declaration.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions September.
 2006 Pearson Education, Inc. All rights reserved Functions and an Introduction to Recursion.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Functions Course conducted by: Md.Raihan ul Masood
IS Program Design and Software Tools Introduction to C++ Programming
RECURSION.
Chapter 7 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 7.13 Recursion […]
Methods Chapter 6.
7 Methods: A Deeper Look [2014Q2-ME2008].
Deitel- C:How to Program (5ed)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
6.11 Function Call Stack and Activation Records
Chapter 6 - Methods Outline 6.1 Introduction 6.2 Program Modules in C# 6.3 Math Class Methods 6.4 Methods 6.5 Method Definitions 6.6 Argument.
6 Functions.
Chapter 5 - Functions Outline 5.1 Introduction
Advanced Programming Chapter 7: Methods: A Deeper Look
Chapter 6 - Functions Outline 5.1 Introduction
Presentation transcript:

Jozef Goetz,  2002 Prentice Hall. All rights reserved. Credits:  Pearson Education, Inc. All rights reserved.

Jozef Goetz, Chapter 7 - Methods Outline 7.1 Introduction 7.2 Packaging Code in C# 7.3 static Methods, static Variables and Class Math 7.4 Declaring Methods with Multiple Parameters 7.5 Notes on Declaring and Using Methods 7.6 Method Call Stack and Activation Records 7.7Argument Promotion and Casting 7.8 The Framework Class Library 7.9 Case Study: Random-Number Generation Scaling and Shifting Random Numbers Random-Number Repeatability for Testing and Debugging 7.10 Case Study: A Game of Chance (Introducing Enumerations) 7.11 Scope of Declarations 7.10 Case Study: A Game of Chance (Introducing Enumerations) 7.11 Scope of Declarations 7.12 Method Overloading 7.15 Recursion 7.16 Passing Arguments: Pass-by-Value vs. Pass-by-Reference

Jozef Goetz, Scope of Declarations Variable and reference attributes: 1.name, 2.type, 3.size, 4.value, 5.scope, 6.duration  Scope  Where an identifier can be referenced/accessed  Local variable can only be used in a block declared  Class scope  Begins at opening brace, ends at closing brace of class  Methods and instance variables  Can be accessed by any method in class  Repeated names causes previous to be hidden until scope ends  Block scope  Begins at identifier's declaration, ends at terminating brace  Have local variables and parameters of methods  When nested blocks and an outer block have an identifier defined; they need unique identifier names otherwise a syntax error  If local variable has same name as instance variable  Instance variable "hidden”

Jozef Goetz, Scope of Declarations; Duration of Identifiers  Variable and reference attributes: name, type, size, value, duration, scope  Duration (lifetime)  the period during which an identifier exists in memory  Automatic duration variables  Created when program control reaches their declaration - local variables in a method or in blocks,  They should be initialized before they can be used  Exist in block they are declared  When block becomes inactive, they are destroyed  Static duration variables  Created when defined and loaded into memory for execution  Their storage is allocated and initialized when their classes are loaded into memory  Exist until program ends  Local variables  Created when declared  Destroyed when the block exits  Instance variables are initialized by the compiler:  Most variables are set to 0  All bool variables are set to false  All reference variables are set to null

 2002 Prentice Hall. All rights reserved. Outline 5 Scoping.cs 1 // Fig ed1 or 7.9 ed5 Scoping.cs 2 // A Scoping example. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; public class Scoping : System.Windows.Forms.Form 12 { 13 private System.ComponentModel.Container components = null; 14 private System.Windows.Forms.Label outputLabel; public int x = 1; // instance variable public Scoping() 19 { 20 InitializeComponent(); int x = 5; // variable local to constructor outputLabel.Text = outputLabel.Text + 25 "local x in method Scoping is " + x; MethodA(); // MethodA has automatic local x; 28 MethodB(); // MethodB uses instance variable x 29 MethodA(); // MethodA creates new automatic local x 30 MethodB(); // instance variable x retains its value outputLabel.Text = outputLabel.Text + 33 "\n\nlocal x in method Scoping is " + x; 34 } This variable has class scope and can be used by any method in the class This variable is local only to Scoping. It hides the value of the global variable Will output the value of 5Remains 5 despite changes to global version of x

 2002 Prentice Hall. All rights reserved. Outline 6 Scoping.cs // Visual Studio.NET-generated code public void MethodA() 39 { 40 int x = 25; // initialized each time a is called outputLabel.Text = outputLabel.Text + 43 "\n\nlocal x in MethodA is " + x + 44 " after entering MethodA"; 45 ++x; 46 outputLabel.Text = outputLabel.Text + 47 "\nlocal x in MethodA is " + x + 48 " before exiting MethodA"; 49 } public void MethodB() 52 { 53 outputLabel.Text = outputLabel.Text + 54 "\n\ninstance variable x is " + x + 55 " on entering MethodB"; 56 x *= 10; 57 outputLabel.Text = outputLabel.Text + 58 "\ninstance varable x is " + x + 59 " on exiting MethodB"; 60 } // main entry point for application 63 [STAThread] 64 static void Main() 65 { 66 Application.Run( new Scoping() ); 67 } } // end of class Scoping Uses the global version of x (1) Uses a new x variable that hides the value of the global x Will permanently change the value of x globally

Jozef Goetz, Method Overloading Procedure/Method overloading  allows procedure/methods with the same name  but different parameter set for each procedure/method 1.Parameter Types 2. Order of parameters 3. Number of parameters  Procedure/Methods cannot be distinguished by return type.  The same signature and different return types result in a syntax error.  Usually perform the same or closely related task  On different data types

 2002 Prentice Hall. All rights reserved. Outline 8 MethodOverload.cs 1 // Fig. 7.10: MethodOverload.cs 2 // Using overloaded methods. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; public class MethodOverload : System.Windows.Forms.Form 12 { 13 private System.ComponentModel.Container components = null; private System.Windows.Forms.Label outputLabel; public MethodOverload() 18 { 19 InitializeComponent(); // call both versions of Square 22 outputLabel.Text = 23 "The square of integer 7 is " + Square( 7 ) + 24 "\nThe square of double 7.5 is " + Square ( 7.5 ); 25 } // Visual Studio.NET-generated code 28 Two versions of the square method are called

 2002 Prentice Hall. All rights reserved. Outline 9 MethodOverload.cs Program Output 29 // first version, takes one integer 30 public int Square ( int x ) 31 { 32 return x * x; 33 } // second version, takes one double 36 public double Square ( double y ) 37 { 38 return y * y; 39 } [STAThread] 42 static void Main() 43 { 44 Application.Run( new MethodOverload() ); 45 } } // end of class MethodOverload One method takes an int as parameters The other version of the method uses a double instead of an integer

 2002 Prentice Hall. All rights reserved. Outline 10 MethodOverload2.cs Program Output 1 // Fig. 7.11: MethodOverload2.cs 2 // Overloaded methods with identical signatures and 3 // different return types. 4 5 using System; 6 7 class MethodOverload2 8 { 9 public int Square( double x ) 10 { 11 return x * x; 12 } // second Square method takes same number, 15 // order and type of arguments, error 16 public double Square( double y ) 17 { 18 return y * y; 19 } // main entry point for application 22 static void Main() 23 { 24 int squareValue = 2; 25 Square( squareValue ); 26 } } // end of class MethodOverload2 This method returns an integer This method returns a double number Since the compiler cannot tell which method to use based on passed values an error is generated

Jozef Goetz, 2015  As of Visual C# 2010 or 2012, methods can have optional parameters that allow the calling method to vary the number of arguments to pass.  An optional parameter specifies a default value that’s assigned to the parameter if the optional argument is omitted.  For example, the method header public int Power( int baseValue, int exponentValue = 2) specifies an optional second parameter.  You can create methods with one or more optional parameters.  All optional parameters must be placed to the right of the method’s non-optional parameters Optional Parameters

Jozef Goetz, 2015  When a parameter has a default value, the caller has the option of passing that particular argument. public int Power( int baseValue, int exponentValue = 2) specifies an optional second parameter. Any call to Power must pass at least an argument for the parameter baseValue, or a compilation error occurs Optional Parameters (Cont.)

Jozef Goetz, 2015  Optionally, a second argument (for the exponentValue parameter) can be passed to Power.  Consider the following calls to Power : Power() Power(10) Power(10, 3)  The first generates a compilation error because this method requires a minimum of one argument.  The second is valid because one argument (10) is being passed—the optional exponentValue is not specified in the method call Optional Parameters (Cont.)

Jozef Goetz, Optional Parameters  The last call Power(10, 3) is also valid -10 is passed as the required argument and 3 is passed as the optional argument.  In the call that passes only one argument (10), parameter exponentValue defaults to 2, which is the default value specified in the method’s header.  Each optional parameter must specify a default value by using an equal (=) sign followed by the value.

Jozef Goetz, 2015 At least base Value must pass. exponentValue is an optional parameter Progr. Error 7.11: Declaring a non-optional parameter to the right of an optional one is a compilation error.

Jozef Goetz, 2015  Visual C# 2010/2012 provides a new feature called named parameters, which enable you to call methods that receive optional parameters by providing only the optional arguments you wish to specify.  Explicitly specify the parameter’s name and value —separated by a colon (:)—in the argument list of the method call. For example: t.SetTime( hour: 12, second: 22 ); // sets the time to 12:00:22 t.SetTime( hour: 12,, second: 22 );// error 7.14 Named Parameters

Jozef Goetz, 2015 t.SetTime( hour: 12, second: 22 ); // sets the time to 12:00:22  The compiler assigns parameter hour the argument 12 and parameter second the argument 22.  The parameter minute is not specified, so the compiler assigns it the default value 0.  It’s also possible to specify the arguments out of order when using named parameters. The arguments for the required parameters must always be supplied.  t.SetTime(12); // sets the time 12:00:00 PM  t.SetTime(12, 30); // sets the time 12:30:00 PM  t.SetTime(12,, 30); // compilation error, C# doesn’t allow // skip an argument 7.14 Named Parameters

Jozef Goetz, Recursion Fig. 7.13Recursive evaluation of 5!, 5 factorial. A recursive def n! = n (n – 1)! (a) Procession of recursive calls. 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 (b) Values returned from each recursive call. Final value = 120 5! = 5 * 24 = 120 is returned 4! = 4 * 6 = 24 is returned 2! = 2 * 1 = 2 is returned 3! = 3 * 2 = 6 is returned 1 returned 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 (a) Each time method calls itself with a slightly simple problem until converges on the base case. Continually breaks problem down to simpler forms. (b) then returns to the previous problem, and a sequence of returns follows up the line until the original problem eventually returns the final result to the caller. While the number to be processed is greater than 1, the function calls itself When the number is 1 or less (the base case), 1 is returned, and each function call can now return an answer until each call has been resolved

Jozef Goetz, General format for many recursive functions if (some condition for which answer is known) // base case solution statement else // general case recursive function call SOME EXAMPLES...

Jozef Goetz, Recursive Definition is a definition in which something is defined in terms of smaller version of itself. int Factorial ( int number ) // Recursive Solution // Pre: number is assigned and number >= 0. { if ( number == 0) //(1) base case return 1 ; //(2) else // general case return number * Factorial ( number - 1 ) ; //(3) //includes the simpler problem }

Jozef Goetz, Recursion  Recursive method  Calls itself (directly or indirectly) through another method  Method knows how to solve only a simples case base case  Method divides problem into 1.Base case 2.Simpler problem –Each time method calls itself with a slightly simple problem until converges on the base case,  Continually breaks problem down to simpler forms  Must converge on the base case in order to end recursion  Each method call remains open (unfinished)  Finishes each call and then finishes itself

Jozef Goetz, int fact ( int number ) // Recursive Solution // Pre: number is assigned and number >= 0. { if ( number == 0) //(1) base case return 1 ; //(2) else // general case return number * fact ( number - 1 ) ; //(3) //includes the simpler problem } //(4) Each method call remains open  Think of a recursive function as having infinitely many copies of itself  Every call to a recursive function has  Its own code  Its own set of parameters and local variables  After completing a particular recursive call  Control goes back to the calling environment, which is the previous call

 2002 Prentice Hall. All rights reserved. Outline 23 FactorialTest.cs 1 // Fig. 7.14: FactorialTest.cs 2 // Recursive Factorial method. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; public class FactorialTest : System.Windows.Forms.Form 12 { 13 private System.ComponentModel.Container components = null; private System.Windows.Forms.Label outputLabel; public FactorialTest() 18 { 19 InitializeComponent(); for ( long i = 0; i <= 10; i++ ) 22 outputLabel.Text += i + "! = " + 23 Factorial( i ) + "\n"; 24 } 25

 2002 Prentice Hall. All rights reserved. Outline 24 FactorialTest.cs Program Output 26 // Visual Studio.NET-generated code public long Factorial( long number ) 29 { 30 if ( number <= 1 ) // base case 31 return 1; else 34 return number * Factorial( number - 1 ); 35 } [STAThread] 38 static void Main() 39 { 40 Application.Run( new FactorialTest()); 41 } } // end of class FactorialTest The Factorial method calls itself (recursion) The recursion ends when the value is less than or equal to 1

Jozef Goetz, Iterative Solution int Factorial ( int number ) // Pre: number is assigned and number >= 0. { int fact = 1; for (int i = 2; i <= number; i++) fact = fact * i; return fact ; }

Jozef Goetz, Example Using Recursion: The Fibonacci Sequence  Fibonacci series  Each number in the series is sum of two previous numbers  e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21 …  Recursive formula fibonacci( 0 ) = 0 fibonacci( 1 ) = 1 fibonacci(n) = fibonacci(n - 1 ) + fibonacci( n – 2 )  Each invocation of the method that does not match one of the base cases results in two additional recursive calls to the method  fibonacci( 0 ) and fibonacci( 1 ) are base cases  Golden ratio  The ratio of successive fibonacci numbers converges on a constant value near  Performance  Fibonacci-style recursive methods exponentially generate method calls (result in an exponential “explosion” of calls) – avoid recursive style for some problems  Hinders performance –Fib(30) has over 2.7 million method calls –Fib(31) has over 4 million method calls –Fib(32) has over 7 million method calls

Jozef Goetz, Example Using Recursion: The Fibonacci Sequence Fig. Set of recursive calls to method Fibonacci (abbreviated as F ). return 1return 0 F( 1 )F( 0 )return 1 F( 3 ) F( 2 )F( 1 ) + return +

 2002 Prentice Hall. All rights reserved. Outline 28 FibonacciTest.cs 1 // Fig ed1: FibonacciTest.cs 2 // Recursive fibonacci method. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; public class FibonacciTest : System.Windows.Forms.Form 12 { 13 private System.ComponentModel.Container components = null; private System.Windows.Forms.Button calculateButton; private System.Windows.Forms.TextBox inputTextBox; private System.Windows.Forms.Label displayLabel; 20 private System.Windows.Forms.Label promptLabel; public FibonacciTest() 23 { 24 InitializeComponent(); 25 } // Visual Studio.NET-generated code 28

 2002 Prentice Hall. All rights reserved. Outline 29 FibonacciTest.cs 29 // call Fibonacci and display results 30 protected void calculateButton_Click( 31 object sender, System.EventArgs e ) 32 { 33 string numberString = ( inputTextBox.Text ); 34 int number = System.Convert.ToInt32( numberString ); 35 int fibonacciNumber = Fibonacci( number ); 36 displayLabel.Text = "Fibonacci Value is " + fibonacciNumber; 37 } // calculates Fibonacci number 40 public int Fibonacci( int number ) 41 { 42 if ( number == 0 || number == 1 ) 43 return number; 44 else 45 return Fibonacci( number - 1 ) + Fibonacci( number - 2 ); 46 } [STAThread] 49 static void Main() 50 { 51 Application.Run( new FibonacciTest() ); 52 } } // end of class FibonacciTest The number uses the Fibonacci method to get its result Calls itself twice, to get the result of the the two previous numbers The recursion ends when the number is 0 or 1

 2002 Prentice Hall. All rights reserved. Outline 30 FibonacciTest.cs Program Output Exercise: Expand by displaying all generated numbers. Exercise: Each number in the series is sum of the last one and the third from the last one. e.g., 0, 1, 1, 1, 2, 3, 4, 6, 9, 13,… First draw the sequence diagram for F(4).

Jozef Goetz, Recursion vs. Iteration  Iteration 1.Uses repetition structures ( for, while or do/while ) 2.Repetition through explicitly use of repetition structure 3.Terminates when loop-continuation condition fails 4.Controls repetition by using a counter 5.No extra calls so it doesn’t consume additional memory  Recursion 1.Uses selection structures ( if, if/else or switch ) 2.Repetition through repeated method calls 3.Terminates when base case is satisfied 4.Controls repetition by dividing problem into simpler one 5.Recursive calls take time and consume additional memory  Both can have infinite loops

Jozef Goetz, Recursion vs. Iteration (cont.)  Recursion negatives:  More overhead than iteration (time expensive)  More memory intensive than iteration (the overhead of repeated method calls) – memory space expensive  Difficult to test and debug positives:  Recursion more naturally mirrors some problems  Often can be implemented with only a few lines of code  Can also be solved iteratively but may take large amount of code  Balance  Choice between performance (iteration) and good software engineering (recursion)  Recursion usually more natural for some problems  Modularizing programs in a neat,  Hierarchical manner promotes good software engineering but it has a prize.

Jozef Goetz, Passing Arguments: Call-By-Value vs. Call-By-Reference  Passing by value  Send a method a copy of the object  Changes to the called method’s copy don’t effect the original variable’s value  When returned are always returned by value  Set by value by default for value-type variables  Passing by reference  Send a method the actual reference point (to the original object in memory)  Causes the variable to be changed throughout the program  When returned are always returned by reference  No overhead of copying large data  Weaken security, b/c the called function can corrupt the caller’s data  Note: The references themselves passed by value  The ref keyword specifies by reference  The out keyword means a called method will initialize the reference variable

 2002 Prentice Hall. All rights reserved. Outline 34 RefOutTest.cs 1 // Fig. 6.8 ed1 or 7.18 ed ed4 and ed5: RefOutTest.cs 2 // Demonstrating ref and out parameters. 3 // 3 methods to calculate the square of an integer 4 using System; 5 using System.Windows.Forms; 6 7 class RefOutTest 8 { 9 // x is passed as a ref int (original value will change) 10 static void SquareRef( ref int x ) 11 { 12 x = x * x; 13 } // original value can be changed and initialized 16 static void SquareOut( out int x ) 17 { 18 x = 6; 19 x = x * x; 20 } // x is passed by value (original value not changed) 23 static void Square( int x ) 24 { 25 x = x * x; 26 } static void Main( string[] args ) 29 { 30 // create a new integer value, set it to 5 31 int y = 5; 32 int z; // declare z, but do not initialize it 33 When passing a value by reference the value will be altered in the rest of the program as well Since x is passed as out the variable can then be initiated in the method Since not specified, this value is defaulted to being passed by value. The value of x will not be changed elsewhere in the program because a duplicate of the variable is created. Since the methods are void they do not need a return value.

 2002 Prentice Hall. All rights reserved. Outline 35 RefOutTest.cs 34 // display original values of y and z 35 string output1 = "The value of y begins as " 36 + y + ", z begins uninitialized.\n\n\n"; // values of y and z are passed by reference 39 RefOutTest.SquareRef( ref y ); // must use ref 40 RefOutTest.SquareOut( out z ); // must use out // display values of y and z after modified by methods 43 // SquareRef and SquareOut 44 string output2 = "After calling SquareRef with y as an " + 45 "argument and SquareOut with z as an argument,\n" + 46 "the values of y and z are:\n\n" + 47 "y: " + y + "\nz: " + z + "\n\n\n"; // values of y and z are passed by value 50 RefOutTest.Square( y ); 51 RefOutTest.Square( z ); // values of y and z will be same as before because Square 54 // did not modify variables directly 55 string output3 = "After calling Square on both x and y, " + 56 "the values of y and z are:\n\n" + 57 "y: " + y + "\nz: " + z + "\n\n"; MessageBox.Show( output1 + output2 + output3, 60 "Using ref and out Parameters", MessageBoxButtons.OK, 61 MessageBoxIcon.Information ); } // end method Main } // end class RefOutTest The calling of the SquareRef and SquareOut methods The calling of the Square method by passing the variables by value

Jozef Goetz, 2015 Find Maximum (and Minimum) 36

Jozef Goetz, 2015 Extra: Find Maximum and Minimum 37

Jozef Goetz, 2015 Class to find MAX 38

Jozef Goetz, 2015 Driver to test CalculateMax() 39