Jozef Goetz, 2011 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.

Slides:



Advertisements
Similar presentations
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Advertisements

Introduction to Computers and Programming Lecture 11: Introduction to Methods Professor: 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.
Introduction to Computers and Programming Introduction to Methods in Java.
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.
Math class methods & User defined methods Math class methods Math.sqrt(4.0) Math.random() java.lang is the library/package that provides Math class methods.
 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.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Functions Part I.
 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.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
1 Lecture 3 Part 1 Functions with math and randomness.
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.
 2002 Prentice Hall. All rights reserved. 1 Week 2: Methods Questions about last week’s revision –C#.NET –.NET Framework –sequence, selection, repetition.
© 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.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
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.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions Xiang Lian The University of Texas – Pan American Edinburg, TX
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
Jozef Goetz,  2002 Prentice Hall. All rights reserved. Credits:  Pearson Education, Inc. All rights reserved.
© 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.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
Jozef Goetz,  2002 Prentice Hall. All rights reserved. Credits:  Pearson Education, Inc. All rights reserved.
 2001 Prentice Hall, Inc. All rights reserved. 1 Introduction to C# Part II.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Craps Game Application Introducing Random-Number Generation and Enum.
Review for Nested loops & Math class methods & User defined methods.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
 2006 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
 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.
Introduction Modules Small pieces of a problem ▴ e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs.
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.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Functions Course conducted by: Md.Raihan ul Masood
Chapter 7 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 7.13 Recursion […]
Methods Chapter 6.
Deitel- C:How to Program (5ed)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
Chapter 10 - JavaScript: Functions
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.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 Methods: A Deeper Look
Chapter 6 - Functions Outline 5.1 Introduction
Program Modules in C# Modules The .NET Framework Class Library (FCL)
6 Methods: A Deeper Look.
6 Functions.
Presentation transcript:

Jozef Goetz,  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. 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,  E pluribus unum. (One composed of many.)  Virgil  Form ever follows function.  Louis Henri Sullivan  O! call back yesterday, bid time return.  William Shakespeare  Call me Ishmael.  Herman Melville

Jozef Goetz,  Answer me in one word.  William Shakespeare  When you call me that, smile!  Owen Wister  There is a point at which methods devour themselves.  Frantz Fanon  Life can only be understood backwards; but it must be lived forwards.  Soren Kierkegaard

Jozef Goetz, Chapter 7: Methods Objectives  To construct programs modularly from small pieces called methods.  To introduce the common math methods available in the Framework Class Library.  To be able to create new methods.  To understand the mechanisms for passing information between methods.  To introduce simulation techniques that use random number generation.  How to use random-number generation to implement game-playing applications  To understand how the visibility of identifiers is limited to specific regions of programs.  To understand how to write and use methods that call themselves – recursive methods  The differences between passing method arguments by value and by reference

Jozef Goetz, Introduction  To develop and maintain a large program  Divide and conquer technique  = Construct a program from small pieces (modules)  Modules in C# are called methods and classes –Each piece more manageable than original program –Facilitate design, implementation, operation and maintenance of large programs

Jozef Goetz, Program Modules in C#  Modules in C#  Methods and classes  allow you to modularize an application by separating its tasks into reusable units.  Programs written by combining new methods and classes with "prepackaged" ones  Available in the. NET Framework Class Library (FCL) => msdn.microsoft.com/en-us/library/ms aspx  When possible, reuse FCL classes and methods.  FCL provides several modules  Rich collection of classes and methods  Mathematical calculations, input/output files, string manipulations..  When possible, reuse Framework Class Library classes and methods.  Programmers can also create modules  e.g., programmer-defined methods  Methods  Invoked by a method call  Returns a result to calling method (caller) - hiding of implementation details  Similar to a boss (caller) asking a worker (called method) to complete a task

Jozef Goetz, Dividing an application into meaningful methods makes the application easier to debug and maintain Software Engineering Observation 7.2 To promote software reusability, every method should be limited to performing a single, well-defined task, and the name of the method should express that task effectively. Error-Prevention Tip 7.1 A small method that performs one task is easier to test and debug than a larger method that performs many tasks. Software Engineering Observation 7.3 If your method might be attempting to perform too many diverse tasks. It is usually best to break such a method into several smaller methods. 7.2 Packaging Code in C# (Cont.)

Jozef Goetz, Fig. 7.1 Hierarchical boss-method/worker-method relationship. Note: The boss method – main doesn’t know how worker 1, worker 2 and worker 4 performs its designated work – hiding of implementation details. worker 1 acts as a “boss method” to worker 4 and worker 5. main worker1worker2worker3 worker4worker5 Dividing an application into meaningful methods makes the application easier to debug and maintain

Jozef Goetz,  The code that calls a method is known as the client code.  An analogy to the method-call-and-return structure is the hierarchical form of management (Figure 7.1).  The boss method does not know how the worker method performs its designated tasks.  The worker may also call other worker methods.  This “hiding” of implementation details promotes good software engineering. Fig. 7.1 | Hierarchical boss-method/worker-method relationship. (Part 1 of 2.) 7.2 Packaging Code in C# (Cont.)

Jozef Goetz, Math Class Methods  Static methods are available when no object of the class have been created  To declare a method as static, place the keyword static before the return type in the method’s declaration.  The Math class – located in namespace System  Allows the user to perform common math calculations  Using methods ClassName.MethodName( argument1, arument2, … )  List of methods are in Fig. 7.2  Console.WriteLine( Math.Sqrt( ) );  Math.sqrt takes an argument of type double returns the square root of its argument –Statement would print 30.0  All Math methods return data type double –Must be invoked using Math and dot operator (. )

Jozef Goetz, Math Class Methods Math defines 2 Constants which are static but you don’t need to specify “static”: Math.PI = … Math.E = … Method arguments may be constants, variables or expressions.

Jozef Goetz,  When objects of a class containing static variables are created, all the objects of that class share one copy of the class’s static variables.  Together the  static variables and  instance variables  represent the fields of a class. 7.3 static Methods, static Variables and Class Math (Cont.)

Jozef Goetz, Why Is Method Main Declared static ?  The Main method is sometimes called the application’s entry point.  Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class.  When you execute your application from the command line, you type the application name, followed by command-line arguments that specify a list of string s separated by spaces.  The execution environment will pass these arguments to the Main method of your application. 7.3 static Methods, static Variables and Class Math (Cont.)

Jozef Goetz, Additional Comments about Method Main  Applications that do not take command-line arguments may omit the string[] args parameter.  The public keyword may be omitted.  You can declare Main with return type int (instead of void ) to enable Main to return an error code with the return statement.  You can declare only one Main method in each class. 7.3 static Methods, static Variables and Class Math (Cont.)

Jozef Goetz,  You can place a Main method in every class you declare.  However, you need to indicate the application’s entry point.  Do this by clicking the menu Project > [ProjectName] Properties... and selecting the class containing the Main method that should be the entry point from the Startup object list box. 7.3 static Methods, static Variables and Class Math (Cont.)

Jozef Goetz,  C# doesn’t allow a static method to access non-static members of the same class directly.  A static method can call only other static methods of the same class directly and can manipulate only static variables in the same class directly. 7.4 Declaring and Using Methods

Jozef Goetz, Methods  Modularize a program by packing code as a method  Variables declared inside methods are local variables  Known only in method defined  Parameters  Communicate information between methods  Are local variables  Benefits (motivation for modularizing a program with methods)  Divide and conquer makes  Manageable program development  Software reusability  Existing standardized methods are building blocks for new programs  Abstraction - hide internal details (library methods)  Avoids code repetition – methods can be called from several locations

Jozef Goetz, Method Definitions  Method definition format: return-value-type method-name ( parameter-list ) //method header { declarations and statements // method body –Redeclaring a method parameter as a local variable in the method’s body is a compilation error. }  Method-name : any valid identifier  Return-value-type : data type of the result  Can return at most one value  Omitting the return type in a method declaration is a syntax error.  void - method returns nothing  Parameter-list : comma separated list, declares parameters

Jozef Goetz, Common Programming Error 7.8  Forgetting to return a value from a method that should return a value is a compilation error.  If a return type other than void is specified, the method must contain a return statement that returns a value consistent with the method’s return type.  Returning a value from a method whose return type has been declared void is a compilation error.

Jozef Goetz, Method Definitions  For each parameter in the method definition :  there must be parameter list compatible with the ton  type  order and  number,  of the corresponding argument in the method call

Jozef Goetz, Method Definitions  Writing a custom method  Body  Contains the code of what the method does  Contains the return value if necessary All methods must be defined inside of a class  Method cannot be defined inside another method  3 way to return control: program flow reaches  1. } - Reaching the function-ending right brace  2. return ;  3. return expression; // returns the resulting value to the caller  Each method should be limited to performing a single, well defined task, no longer that one page  The name of the method (self-explanatory) should express that task effectively.

Jozef Goetz, Software Engineering Observation 7.4  A method that has many parameters may be performing too many tasks.  Consider dividing the method into smaller methods that perform the separate tasks.  As a guideline, try to fit the method header on one line if possible.

Jozef Goetz, Method Definitions Until now, our programs have used methods of class Console to obtain:  User input from the command line  Output either to the command prompt or in messageBox  Minuses: the command prompt can obtain only 1 value (or series of the same data type) at a time from the user, and a msg dialog can display only 1 msg GUI application can read multiple inputs simultaneously and display/output many pieces of data at once – see next program

 2002 Prentice Hall. All rights reserved. Outline 25 Subtract.cs 1 // Fig. 6.3 ed1: SquareInt.cs - The windows application 2 // A programmer-defined Square method. 3 // calculates of the integers from 1 to 10 4 using System; // includes basic data types 5 using System.Drawing; // for graphics capabilities 6 using System.Collections; // for complex data structures 7 using System.ComponentModel; // controls component behavior 8 using System.Windows.Forms; // for GUI development 9 using System.Data; // for reading outside data // form used to display results of squaring 10 numbers 12 public class SquareIntegers : System.Windows.Forms.Form 13 { 14 private System.ComponentModel.Container components = null; // label containing results 17 private System.Windows.Forms.Label outputLabel; public SquareIntegers() 20 { 21 // Required for Windows Form Designer support 22 InitializeComponent(); // to create objects int result; // store result of call to method Square 25 Start of class SquareInteger. It implements System.Windows.Forms.Form Start of the SquareIntegers method This is the method’s variables. They can only be used within the method.

 2002 Prentice Hall. All rights reserved. Outline 26 Subtract.cs 26 // loop 10 times 27 for ( int counter = 1; counter <= 10; counter++ ) 28 { 29 // calculate square of counter and store in result 30 result = Square( counter ); // append result to output string 33 outputLabel.Text += "The square of " + counter + 34 " is " + result + "\n"; 35 } } // end SquareIntegers // Clean up any resources being used. 40 protected override void Dispose( bool disposing ) 41 { 42 // Visual Studio.NET-generated code for method Dispose 43 } // Required method for Designer support 46 private void InitializeComponent() 47 { 48 // Visual Studio.NET generated code 49 // for method InitializeComponent 50 } 51 The main body of the SquareIntegers method A call to the Square method. The counter variable is passed to it for use. The return value is stored in result

 2002 Prentice Hall. All rights reserved. Outline 27 Subtract.cs Program Output 52 // The main entry point for the application. 53 [STAThread] 54 static void Main() // no arguments 55 { 56 Application.Run( new SquareIntegers() ); 57 } // Square method definition 60 int Square( int y ) 61 { 62 return y * y; // return square of y } // end method Square } // end of class SquareIntegers The Square method. Receives one integer and returns an integer The method returns the passed variable multiplied by itself

Jozef Goetz, Method Definitions (cont.)  When method call encountered  Control is transferred from point of invocation to method  Returning control  If nothing returned: return; –Or until reaches right brace  If value returned: return expression ; –Returns the value of expression  Example user-defined method: public int Square( int y ) { return y * y }

Jozef Goetz, Outline  Maximum Finder.cs Enter three floating-point values, pressing 'Enter' after each one: Maximum is: 3.33

Jozef Goetz, Outline  MaximumFinderTest.cs

 2002 Prentice Hall. All rights reserved. Outline 31 MaximumValue.cs 1 // Fig. 7.3 ed1: MaximumValue.cs 2// Finding the maximum of three doubles using the FCL library 4 using System; // in a single class 5 6 class MaximumValue 7 { 8 // main entry point for application 9 static void Main( string[] args ) 10 { 11 // obtain user input and convert to double 12 Console.Write( "Enter first floating-point value: " ); 13 double number1 = Double.Parse( Console.ReadLine() ); 14 // or use Convert.ToDouble ( Console.ReadLine() ); 15 Console.Write( "Enter second floating-point value: " ); 16 double number2 = Double.Parse( Console.ReadLine() ); Console.Write( "Enter third floating-point value: " ); 19 double number3 = Double.Parse( Console.ReadLine() ); // call method Maximum to determine largest value 22 double max = Maximum( number1, number2, number3 ); // display maximum value 25 Console.WriteLine("\nmaximum is: " + max ); } // end method Main The program gets three values from the user The three values are then passed to the Maximum method for use Enter first floating-point value: 37.3 Enter second floating-point value: Enter third floating-point value: maximum is: 99.32

 2002 Prentice Hall. All rights reserved. Outline 32 MaximumValue.cs Program Output // Maximum method uses method Math.Max to help determine 30 // the maximum value 31 static double Maximum( double x, double y, double z ) 32 { 33 return Math.Max( x, Math.Max( y, z ) ); } // end method Maximum } // end class MaximumValue Enter first floating-point value: 37.3 Enter second floating-point value: Enter third floating-point value: maximum is: The Maximum method receives 3 variables and returns the largest one The use of Math.Max uses the Max method in class Math. The dot operator is used to call it. Exc: Convert the console app. into the window application.

Jozef Goetz, Common Programming Error 7.1  Declaring method parameters of the same type as  float x, y instead of  float x, float y is a syntax error —a type is required for each parameter in the parameter list.

Jozef Goetz, Argument Promotion  Implicit Conversion or Coercion of arguments  Object is converted to a needed type implicitly  Only done if complier knows no data will be lost  Forcing arguments to appropriate type to pass to method  e.g., Console.WriteLine( Math.Sqrt( 4 ) ); –Evaluates Math.Sqrt( 4 ) and displays 2 –So it converts 4 to the double (which is required for the Sqrt arguments) value 4.0 before passing the value to Math.Sqrt without changing the value  C# does not allow narrowing without explicit cast operation  Explicit Conversion  Object is manually converted  Required if there could be a loss of data  Widening conversion  Make an object that of a derived class more complex without losing data  Narrowing conversion  Make an object that of a base class and cause some data loss –If y = 4.5 the method call –square( (int) y ) –explicitly casts (converts) the value of y to an integer, so it returns 16, not 20.25

Jozef Goetz, Argument Promotion  Promotion rules  Specify how to convert types without data loss  Apply to  a mixed-type expression  primitive data-type values passed as arguments to methods  The type of each value in a mixed-type expression is promoted to the “highest” type in the expression (actually, the expression uses a temporary copy of each value; the original values remain unchanged)

Jozef Goetz, Argument Promotion p.238, 935

Jozef Goetz, Value Types and Reference Types  Value types – they are portable across platform  Contains data of the specified type:  The buil-in values types: int, bool see previous slides  integral types: sbyte, byte, short, int, long etc.  floating types: float and double  decimal  bool  Programmer created  struct s  enum erations (Chapter 7)  Reference types  Refererence to objects  Contain an address to a spot in memory where the data is  Build-in reference types: string and object  Programmer created  Classes (Chapter 10)  Interfaces (Chapter 12)  Delegates (Chapter 12)  All values are 32bit allowing cross-platform use

Jozef Goetz, C# Namespaces vs FCL  Namespace (used packages in Java)  A group of classes and their methods  FCL (Framework Class Library) is composed of namespaces  Namespaces are stored in.dll files called assemblies  Must add a reference to the appropriate assembly –assembly reference namespace System are added automatically  A list of the FLC namespaces are in Fig. 7.5  Familiarize yourself with the classes and methods provided by the FCL msdn2.microsoft.com/en-us/library/ms .NET Framework, class library for info on all namespaces  Included in a program with the using keyword (import in Java)

Jozef Goetz, C# Namespaces

Jozef Goetz, C# Namespaces

Jozef Goetz, C# Namespaces

Jozef Goetz, NET Framework Namespaces & Classes

Jozef Goetz, NET Framework

Jozef Goetz, Random Number Generation  Class Random  Within namespace System  Truly random  The numbers are generated using an equations with a seed –The seed is usually the exact time of day  randomObject.Next ()  Returns a number from 0 to Int32.MaxValue –Int32.MaxValue = 2,147,483,647  randomObject.Next ( x )  Returns a value from 0 up to but not including x  randomObject.Next ( x, y )  Returns a number between x and up to but not including y

 2002 Prentice Hall. All rights reserved. Outline 45 RandomInt.cs 1 // Fig. 7.6 ed4: RandomInt.cs 2 // Random integers. 3 4 using System; 5 using System.Windows.Forms; 6 7 // calculates and displays 20 random integers 8 class RandomInt 9 { 10 // main entry point for application 11 static void Main( string[] args ) 12 { 13 int value; 14 string output = ""; Random randomInteger = new Random(); // located in System // loop 20 times 19 for ( int i = 1; i <= 20; i++ ) 20 { 21 // pick random integer between 1 and 6 22 value = randomInteger.Next( 1, 7 ); 23 output += value + " "; // append value to output // if counter divisible by 5, append newline 26 if ( i % 5 == 0 ) 27 output += "\n"; } // end for structure 30 Creates a new Random objectWill set value to a random number from1 up to but not including 7 Format the output to only have 5 numbers per line

 2002 Prentice Hall. All rights reserved. Outline 46 RandomInt.cs Program Output 31 MessageBox.Show( output, "20 Random Numbers from 1 to 6", 32 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end Main } // end class RandomInt Display the output in a message box

 2002 Prentice Hall. All rights reserved. Outline 47 RollDie.cs 1 // Fig. 6.10ed1 or 7.7ed3: RollDie.cs //show it 2// Rolling 4 dice at a time and displays an image of 3// each die in the window. 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; 10 using System.IO; // enables reading data from files // form simulates the rolling of 12 dice, 13 // and displays them 14 public class RollDie : System.Windows.Forms.Form 15 { 16 private System.ComponentModel.Container components = null; private System.Windows.Forms.Button rollButton; private System.Windows.Forms.Label dieLabel2; 21 private System.Windows.Forms.Label dieLabel1; 22 private System.Windows.Forms.Label dieLabel3; 23 private System.Windows.Forms.Label dieLabel4; private Random randomNumber = new Random(); public RollDie() 28 { 29 InitializeComponent(); 30 } // Visual Studio.NET-generated code 33

 2002 Prentice Hall. All rights reserved. Outline 48 RollDie.cs 34 // method called when rollButton clicked, 35 // passes labels to another method 36 protected void rollButton_Click( 37 object sender, System.EventArgs e ) 38 { 39 // pass the labels to a method that will 40 // randomly assign a face to each die 41 DisplayDie( dieLabel1 ); 42 DisplayDie( dieLabel2 ); 43 DisplayDie( dieLabel3 ); 44 DisplayDie( dieLabel4 ); } // end rollButton_Click // determines image to be displayed by current die 49 public void DisplayDie( Label dieLabel ) 50 { 51 int face = 1 + randomNumber.Next( 6 ); // displays image specified by filename 54 dieLabel.Image = Image.FromFile( 55 Directory.GetCurrentDirectory() + 56 "\\images\\die" + face +".gif" ); 57 } // main entry point for application 60 [STAThread] 61 static void Main() 62 { 63 Application.Run( new RollDie() ); 64 } } // end class RollDie Pass the labels to be assigned dataWill return a random integer from 1 up to 6

 2002 Prentice Hall. All rights reserved. Outline 49 RollDie.cs Program Output

Jozef Goetz, 2011 © by Pearson Education, Inc. All Rights Reserved.

Jozef Goetz, 2011 © by Pearson Education, Inc. All Rights Reserved.

Jozef Goetz, 2011 © by Pearson Education, Inc. All Rights Reserved.

 2002 Prentice Hall. All rights reserved. Outline 53 RollDie2.cs 1 // Fig ed1 : RollDie2.cs 2 // Rolling 12 dice with frequency chart. 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; 10 using System.IO; // displays the different dice and frequency information 13 public class RollDie2 : System.Windows.Forms.Form 14 { 15 private System.ComponentModel.Container components = null; private System.Windows.Forms.Button rollButton; private System.Windows.Forms.RichTextBox displayTextBox; private System.Windows.Forms.Label dieLabel1; 22 private System.Windows.Forms.Label dieLabel2; 23 private System.Windows.Forms.Label dieLabel3; 24 private System.Windows.Forms.Label dieLabel4; 25 private System.Windows.Forms.Label dieLabel5; 26 private System.Windows.Forms.Label dieLabel6; 27 private System.Windows.Forms.Label dieLabel7; 28 private System.Windows.Forms.Label dieLabel8; 29 private System.Windows.Forms.Label dieLabel9; 30 private System.Windows.Forms.Label dieLabel10; 31 private System.Windows.Forms.Label dieLabel11; 32 private System.Windows.Forms.Label dieLabel12; private Random randomNumber = new Random();

 2002 Prentice Hall. All rights reserved. Outline 54 RollDie2.cs private int ones, twos, threes, fours, fives, sixes; public RollDie2() 39 { 40 InitializeComponent(); 41 ones = twos = threes = fours = fives = sixes = 0; 42 } // Visual Studio.NET-generated code // simulates roll by calling DisplayDie for 47 // each label and displaying the results 48 protected void rollButton_Click( 49 object sender, System.EventArgs e ) 50 { 51 // pass 12 labels to a method that will 52 // randomly assign a face to each die 53 DisplayDie( dieLabel1 ); 54 DisplayDie( dieLabel2 ); 55 DisplayDie( dieLabel3 ); 56 DisplayDie( dieLabel4 ); 57 DisplayDie( dieLabel5 ); 58 DisplayDie( dieLabel6 ); 59 DisplayDie( dieLabel7 ); 60 DisplayDie( dieLabel8 ); 61 DisplayDie( dieLabel9 ); 62 DisplayDie( dieLabel10 ); 63 DisplayDie( dieLabel11 ); 64 DisplayDie( dieLabel12 ); double total = ones + twos + threes + fours + fives + sixes; 67 Sets all of the variables to 0 Pass the label to be assigned a random number

 2002 Prentice Hall. All rights reserved. Outline 55 RollDie2.cs 68 // display the current frequency values 69 displayTextBox.Text = "Face\t\tFrequency\tPercent\n1\t\t" + 70 ones + "\t\t" + 71 String.Format( "{0:F2}", ones / total * 100 ) + 72 "%\n2\t\t" + twos + "\t\t" + 73 String.Format( "{0:F2}", twos / total * 100 ) + 74 "%\n3\t\t" + threes + "\t\t" + 75 String.Format( "{0:F2}", threes / total * 100 ) + 76 "%\n4\t\t" + fours + "\t\t" + 77 String.Format( "{0:F2}", fours / total * 100 ) + 78 "%\n5\t\t" + fives + "\t\t" + 79 String.Format( "{0:F2}", fives / total * 100 ) + 80 "%\n6\t\t" + sixes + "\t\t" + 81 String.Format( "{0:F2}", sixes / total * 100 ) + "%"; } // end rollButton_Click // display the current die, and modify frequency values 86 public void DisplayDie( Label dieLabel ) 87 { 88 int face = 1 + randomNumber.Next( 6 ); dieLabel.Image = Image.FromFile( 91 Directory.GetCurrentDirectory() + 92 "\\images\\die" + face + ".gif" ); 93 Assign a random face to the label based on the number generated Displays to the user the amount of times each dice number has shown up

 2002 Prentice Hall. All rights reserved. Outline 56 RollDie2.cs 94 // add one to frequency of current face 95 switch ( face ) 96 { 97 case 1: ones++; 98 break; case 2: twos++; 101 break; case 3: threes++; 104 break; case 4: fours++; 107 break; case 5: fives++; 110 break; case 6: sixes++; 113 break; } // end switch } // end DisplayDie // The main entry point for the application. 120 [STAThread] 121 static void Main() 122 { 123 Application.Run( new RollDie2() ); 124 } } // end of class RollDie2 A switch statement is used to keep track of number of each die rolled

 2002 Prentice Hall. All rights reserved. Outline 57 RollDie2.cs Program Output

Jozef Goetz, Example: Game of Chance  Craps simulation - the most popular games of chance  A player has 2 dice. Each dice has six faces.  The player must roll two dice on the first and all subsequent rolls 1.Roll dice first time  If sum equals 7 or 11, the player wins on the first throw (called “craps”)  If sum equals 2, 3 or 12, the player loses  Any other sum (4, 5, 6, 8, 9, 10) is that player’s point 2.Keep rolling dice until…  Sum matches player’s point –Player wins  Sum equals 7 –Player loses  GUI controls  A GroupBox  Holds other controls  Manages/organizes them  A PictureBox  Used to display a picture on the form

 2002 Prentice Hall. All rights reserved. Outline 59 CrapsGame.cs 1 // Fig ed1: CrapsGame.cs 2 // Craps Game 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; 10 using System.IO; public class CrapsGame : System.Windows.Forms.Form 13 { 14 private System.ComponentModel.Container components = null; private System.Windows.Forms.PictureBox imgPointDie1; //upper one 16 private System.Windows.Forms.PictureBox imgPointDie2; //upper one 17 private System.Windows.Forms.PictureBox imgDie2; //lower one 18 private System.Windows.Forms.PictureBox imgDie1; //lower one private System.Windows.Forms.Label lblStatus; private System.Windows.Forms.Button rollButton; 23 private System.Windows.Forms.Button playButton; private System.Windows.Forms.GroupBox fraPoint; // declare other variables 30 int myPoint; 31 int myDie1; 32 int myDie2; 33 imgDie1 imgPointDie1

 2002 Prentice Hall. All rights reserved. Outline 60 CrapsGame.cs 34 public enum DiceNames 35 { 36 SNAKE_EYES = 2, 37 TREY = 3, 38 CRAPS = 7, 39 YO_LEVEN = 11, 40 BOX_CARS = 12, 41 } public CrapsGame() 44 { 45 InitializeComponent(); 46 } // Visual Studio.NET-generated code // simulate next roll and result of that roll 51 protected void rollButton_Click( 52 object sender, System.EventArgs e ) 53 { 54 int sum; 55 sum = rollDice(); //at least executed if ( sum == myPoint ) // Sum matches player’s point 58 { 59 lblStatus.Text = "You Win!!!"; 60 rollButton.Enabled = false; 61 playButton.Enabled = true; 62 } Creates an enumeration of the constant values in craps When the second rolled sum equals the first rolled sum the player wins

 2002 Prentice Hall. All rights reserved. Outline 61 CrapsGame.cs 63 else 64 if ( sum == ( int )DiceNames.CRAPS ) // = 7 65 { 66 lblStatus.Text = "Sorry. You lose."; 67 rollButton.Enabled = false; 68 playButton.Enabled = true; 69 } } // end rollButton_Click // simulate first roll and result of that roll 74 protected void playButton_Click( 75 object sender, System.EventArgs e ) 76 { 77 int sum; 78 myPoint = 0; 79 fraPoint.Text = "Point"; 80 lblStatus.Text = ""; 81 imgPointDie1.Image = null; //upper one 82 imgPointDie2.Image = null; //upper one sum = rollDice(); 85 If the second roll equals CRAPS (7), then the player loses

 2002 Prentice Hall. All rights reserved. Outline 62 CrapsGame.cs 86 switch ( sum ) 87 { 88 case ( int )DiceNames.CRAPS: // = 7 89 case ( int )DiceNames.YO_LEVEN: 90 rollButton.Enabled = false; // disable Roll button 91 lblStatus.Text = "You Win!!!"; 92 break; 93 case ( int )DiceNames.SNAKE_EYES: // = 2 94 case ( int )DiceNames.TREY: // = 3 95 case ( int )DiceNames.BOX_CARS: // = rollButton.Enabled = false; 97 lblStatus.Text = "Sorry. You lose."; 98 break; 99 default: 100 myPoint = sum; 101 fraPoint.Text = "Point is " + sum; 102 lblStatus.Text = "Roll Again"; 103 displayDie( imgPointDie1, myDie1 );//upper one 104 displayDie( imgPointDie2, myDie2 );//upper one 105 playButton.Enabled = false; 106 rollButton.Enabled = true; 107 break; } // end switch } // end playButton_Click private void displayDie( PictureBox imgDie, int face ) 114 { 115 imgDie.Image = Image.FromFile( 116 Directory.GetCurrentDirectory() "\\images\\die" + face + ".gif" ); 118 } 119 If on the first roll the players gets a 7 or an 11 they win If the first roll is a 2, 3 or 12, the player loses. Any other number allows the player to roll again imgPointDie1 imgDie1

 2002 Prentice Hall. All rights reserved. Outline 63 CrapsGame.cs 120 // simulates the rolling of two dice 121 private int rollDice() 122 { 123 int die1, die2, dieSum; 124 Random randomNumber = new Random(); die1 = randomNumber.Next( 1, 7 ); 127 die2 = randomNumber.Next( 1, 7 ); displayDie( imgDie1, die1 ); //lower one 130 displayDie( imgDie2, die2 ); //lower one myDie1 = die1; 133 myDie2 = die2; 134 dieSum = die1 + die2; 135 return dieSum; } // end rollDice // main entry point for application 140 [STAThread] 141 static void Main() 142 { 143 Application.Run(new CrapsGame()); 144 } } // end of class CrapsGame Generates two random numbers, one for each die imgDie1 imgPointDie1

 2002 Prentice Hall. All rights reserved. Outline 64 CrapsGame.cs Program Output

Jozef Goetz, Outline  CrapsTest. cs

Jozef Goetz, Outline  Craps.cs  (1 of 4)

Jozef Goetz, Outline  Craps.cs  (2 of 4) Player rolled = 6 Point is 6 Player rolled = 4 Player rolled = 10 Player rolled = 7 Player loses

Jozef Goetz, Outline  Craps.cs  (3 of 4) Player rolled = 6 Point is 6 Player rolled = 4 Player rolled = 10 Player rolled = 7 Player loses Player rolled = 7 Player wins Player rolled = 3 Player loses

Jozef Goetz, Outline  Craps.cs  (4 of 4) Player rolled = 7 Player wins Player rolled = 3 Player loses

Jozef Goetz, Outline  CrapsTest.cs

Jozef Goetz, Scope of Declarations Variable and reference attributes: 1.name, 2.type, 3.size, 4.value, 5.scope, 6.duration  Scope  Where 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 73 Scoping.cs 1 // Fig ed1 or 7.11 ed3: 7.9 ed4 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 74 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 76 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 77 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 78 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, 2011  As of Visual C# 2010, 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, 2011  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.) © by Pearson Education, Inc. All Rights Reserved.

Jozef Goetz, 2011  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.) © by Pearson Education, Inc. All Rights Reserved.

Jozef Goetz, Optional Parameters  The last call 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, 2011 At least base Value must pass. exponentValue is an optional parameter Prog. Error 7.11: Declaring a non-optional parameter to the right of an optional one is a compilation error.

Jozef Goetz, 2011  Visual C# 2010 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: Named Parameters © by Pearson Education, Inc. All Rights Reserved.

Jozef Goetz, 2011  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 Named Parameters © by Pearson Education, Inc. All Rights Reserved.

Jozef Goetz, Recursion Fig. 9.10Recursive 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, (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. Continually breaks problem down to simpler forms. 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, Recursive Functions  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

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

 2002 Prentice Hall. All rights reserved. Outline 92 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 93 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 97 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 98 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 99 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  Uses repetition structures ( for, while or do/while )  Repetition through explicitly use of repetition structure  Terminates when loop-continuation condition fails  Controls repetition by using a counter  No extra calls so it doesn’t consume additional memory  Recursion  Uses selection structures ( if, if/else or switch )  Repetition through repeated method calls  Terminates when base case is satisfied  Controls repetition by dividing problem into simpler one  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 103 RefOutTest.cs 1 // Fig. 6.8 ed1 or 7.18 ed ed4: 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 104 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 ); 40 RefOutTest.SquareOut( out z ); // 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, 2011 Extra: Find Maximum (and Minimum) 105

Jozef Goetz, 2011 Class to find MAX 106

Jozef Goetz, 2011 Driver to test CalculateMax() 107