Download presentation
Presentation is loading. Please wait.
Published byΦιλήμων Αλεξιάδης Modified over 6 years ago
1
Chapter 6 - Methods Outline Introduction Program Modules in C# Math Class Methods Methods Method Definitions Argument Promotion C# Namespaces Value Types and Reference Types Passing Arguments: Call-by-Value vs. Call-by-Reference Random-Number Generation Example: Game of Chance Duration of Identifiers Scope Rules Recursion Example Using Recursion: The Fibonacci Series Recursion vs. Iteration Method Overloading
2
The .NET Framework Class Library (FCL)
6.2 Program Modules in C# Modules Class Method Enables use of classes or methods without knowledge of how they work, just what they should do The .NET Framework Class Library (FCL) Helps to increase reusability Console MessageBox
3
6.2 Program Modules in C# boss worker1 worker2 worker3 worker4 worker5
Fig. 6.1 Hierarchical boss method/worker method relationship.
4
6.3 Math Class Methods The Math class
Allows the user to perform common math calculations Using methods ClassName.MethodName( argument1, arument2, … ) List of methods are in Fig. 6.2 Constants Math.PI = … Math.E = …
5
6.3 Math Class Methods
6
6.4 Methods Variables Reasons for using
Declared in a method = local variables Declared outside a method = global variables Only the method that defines them know they exist Send parameters to communicate with other methods Reasons for using Divide and conquer Reusability Use classes and methods as building blocks for new ones Cut down on repetition Methods can be called from anywhere in a program
7
Writing a custom method
6.5 Method Definitions Writing a custom method Header ReturnType Properties Name( Param1, Param2, … ) Body Contains the code of what the method does Contains the return value if necessary For uses call elsewhere in program Pass parameters if needed All methods must be defined inside of a class
8
Start of class SquareInteger. It implements System.Windows.Forms.Form
1 // Fig. 6.3: SquareInt.cs 2 // A programmer-defined Square method 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 { private System.ComponentModel.Container components = null; // label containing results private System.Windows.Forms.Label outputLabel; public SquareIntegers() { // Required for Windows Form Designer support InitializeComponent(); int result; // store result of call to method Square 25 Subtract.cs 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.
9
The main body of the SquareIntegers method Subtract.cs
// loop 10 times for ( int counter = 1; counter <= 10; counter++ ) { // calculate square of counter and store in result result = Square( counter ); 31 // append result to output string outputLabel.Text += "The square of " + counter + " is " + result + "\n"; } 36 } // end SquareIntegers 38 // Clean up any resources being used. protected override void Dispose( bool disposing ) { // Visual Studio .NET-generated code for method Dispose } 44 // Required method for Designer support private void InitializeComponent() { // Visual Studio .NET generated code // for method InitializeComponent } 51 The main body of the SquareIntegers method Subtract.cs A call to the Square method. The counter variable is passed to it for use. The return value is stored in result
10
Subtract.cs Program Output
// The main entry point for the application. [STAThread] static void Main() { Application.Run( new SquareIntegers() ); } 58 // Square method definition int Square( int y ) { return y * y; // return square of y 63 } // end method Square 65 66 } // end of class SquareIntegers Subtract.cs Program Output The Square method. Receives one integer and returns an integer The method returns the passed variable multiplied by itself
11
The program gets three values from the user
1 // Fig. 6.4: MaximumValue.cs 2 // Finding the maximum of three doubles. 3 4 using System; 5 6 class MaximumValue 7 { // main entry point for application static void Main( string[] args ) { // obtain user input and convert to double Console.Write( "Enter first floating-point value: " ); double number1 = Double.Parse( Console.ReadLine() ); 14 Console.Write( "Enter second floating-point value: " ); double number2 = Double.Parse( Console.ReadLine() ); 17 Console.Write( "Enter third floating-point value: " ); double number3 = Double.Parse( Console.ReadLine() ); 20 // call method Maximum to determine largest value double max = Maximum( number1, number2, number3 ); 23 // display maximum value Console.WriteLine("\nmaximum is: " + max ); 26 } // end method Main MaximumValue.cs The program gets three values from the user The three values are then passed to the Maximum method for use
12
MaximumValue.cs Program Output
28 // Maximum method uses method Math.Max to help determine // the maximum value static double Maximum( double x, double y, double z ) { return Math.Max( x, Math.Max( y, z ) ); 34 } // end method Maximum 36 37 } // end class MaximumValue MaximumValue.cs Program Output 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. Enter first floating-point value: 37.3 Enter second floating-point value: 99.32 Enter third floating-point value: maximum is: 99.32
13
6.6 Argument Promotion Implicit Conversion Explicit Conversion
Object is converted to a needed type implicitly Only done if complier knows no data will be lost Explicit Conversion Object is manually converted Required if there could be a loss of data Widening Make an object that of a derived class and more complex Narrowing Make an object that of a base class and cause some data loss
14
6.6 Argument Promotion
15
6.7 C# Namespaces Namespace A group of classes and their methods
FCL is composed of namespaces Namespaces are stored in .dll files called assemblies A list of the FLC namespaces are in Fig. 6.6 .NET Framework, class library for info on all namespaces Included in a program with the using keyword
16
6.7 C# Namespaces
17
6.8 Value Types and Reference Types
Contains data of the specified type Programmer created structs enumerations (Chapter 8) Reference types Contain an address to a spot in memory where the data is Programmer create Classes (Chapter 8) Interfaces (Chapter 8) Delegates (Chapter 9) All values are 32bit allowing cross-platform use
18
6.9 Passing Arguments: Call-By-Value vs. Call-By-Reference
Passing by value Send a method a copy of the object When returned are always returned by value Set by value by default Passing by reference Send a method the actual reference point Causes the variable to be changed throughout the program When returned are always returned by reference The ref keyword specifies by reference The out keyword means a called method will initialize it
19
Since the methods are void they do not need a return value.
1 // Fig. 6.8: RefOutTest.cs 2 // Demonstrating ref and out parameters. 3 4 using System; 5 using System.Windows.Forms; 6 7 class RefOutTest 8 { // x is passed as a ref int (original value will change) static void SquareRef( ref int x ) { x = x * x; } 14 // original value can be changed and initialized static void SquareOut( out int x ) { x = 6; x = x * x; } 21 // x is passed by value (original value not changed) static void Square( int x ) { x = x * x; } 27 static void Main( string[] args ) { // create a new integer value, set it to 5 int y = 5; int z; // declare z, but do not initialize it 33 RefOutTest.cs When passing a value by reference the value will be altered in the rest of the program as well Since the methods are void they do not need a return value. Since x is passed as out the variable can then be initialed 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.
20
The calling of the SquareRef and SquareOut methods
// display original values of y and z string output1 = "The value of y begins as " y + ", z begins uninitialized.\n\n\n"; 37 // values of y and z are passed by value RefOutTest.SquareRef( ref y ); RefOutTest.SquareOut( out z ); 41 // display values of y and z after modified by methods // SquareRef and SquareOut string output2 = "After calling SquareRef with y as an " + "argument and SquareOut with z as an argument,\n" + "the values of y and z are:\n\n" + "y: " + y + "\nz: " + z + "\n\n\n"; 48 // values of y and z are passed by value RefOutTest.Square( y ); RefOutTest.Square( z ); 52 // values of y and z will be same as before because Square // did not modify variables directly string output3 = "After calling Square on both x and y, " + "the values of y and z are:\n\n" + "y: " + y + "\nz: " + z + "\n\n"; 58 MessageBox.Show( output1 + output2 + output3, "Using ref and out Parameters", MessageBoxButtons.OK, MessageBoxIcon.Information ); 62 } // end method Main 64 65 } // end class RefOutTest RefOutTest.cs The calling of the SquareRef and SquareOut methods The calling of the SquareRef and SquareOut methods by passing the variables by value
21
RefOutTest.cs Program Output
22
6.10 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
23
Creates a new Random object
1 // Fig. 6.9: 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 { // main entry point for application static void Main( string[] args ) { int value; string output = ""; 15 Random randomInteger = new Random(); 17 // loop 20 times for ( int i = 1; i <= 20; i++ ) { // pick random integer between 1 and 6 value = randomInteger.Next( 1, 7 ); output += value + " "; // append value to output 24 // if counter divisible by 5, append newline if ( i % 5 == 0 ) output += "\n"; 28 } // end for structure 30 RandomInt.cs Creates a new Random object Will set value to a random number from1 up to but not including 7 Format the output to only have 5 numbers per line
24
RandomInt.cs Program Output
MessageBox.Show( output, "20 Random Numbers from 1 to 6", MessageBoxButtons.OK, MessageBoxIcon.Information ); 33 } // end Main 35 36 } // end class RandomInt Display the output in a message box RandomInt.cs Program Output
25
RollDie.cs 1 // Fig. 6.10: RollDie.cs 2 // Rolling 12 dice. 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 11 12 // form simulates the rolling of 12 dice, 13 // and displays them 14 public class RollDie : System.Windows.Forms.Form 15 { private System.ComponentModel.Container components = null; 17 private System.Windows.Forms.Button rollButton; 19 private System.Windows.Forms.Label dieLabel2; private System.Windows.Forms.Label dieLabel1; private System.Windows.Forms.Label dieLabel3; private System.Windows.Forms.Label dieLabel4; 24 private Random randomNumber = new Random(); 26 public RollDie() { InitializeComponent(); } 31 // Visual Studio .NET-generated code 33 RollDie.cs
26
Pass the labels to be assigned data
// method called when rollButton clicked, // passes labels to another method protected void rollButton_Click( object sender, System.EventArgs e ) { // pass the labels to a method that will // randomly assign a face to each die DisplayDie( dieLabel1 ); DisplayDie( dieLabel2 ); DisplayDie( dieLabel3 ); DisplayDie( dieLabel4 ); 45 } // end rollButton_Click 47 // determines image to be displayed by current die public void DisplayDie( Label dieLabel ) { int face = 1 + randomNumber.Next( 6 ); 52 // displays image specified by filename dieLabel.Image = Image.FromFile( Directory.GetCurrentDirectory() + "\\images\\die" + face +".gif" ); } 58 // main entry point for application [STAThread] static void Main() { Application.Run( new RollDie() ); } 65 66 } // end class RollDie RollDie.cs Pass the labels to be assigned data Will return a random integer from 0 up to 6
27
RollDie.cs Program Output
28
RollDie2.cs 1 // Fig. 6.11: 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; 11 12 // displays the different dice and frequency information 13 public class RollDie2 : System.Windows.Forms.Form 14 { private System.ComponentModel.Container components = null; 16 private System.Windows.Forms.Button rollButton; 18 private System.Windows.Forms.RichTextBox displayTextBox; 20 private System.Windows.Forms.Label dieLabel1; private System.Windows.Forms.Label dieLabel2; private System.Windows.Forms.Label dieLabel3; private System.Windows.Forms.Label dieLabel4; private System.Windows.Forms.Label dieLabel5; private System.Windows.Forms.Label dieLabel6; private System.Windows.Forms.Label dieLabel7; private System.Windows.Forms.Label dieLabel8; private System.Windows.Forms.Label dieLabel9; private System.Windows.Forms.Label dieLabel10; private System.Windows.Forms.Label dieLabel11; private System.Windows.Forms.Label dieLabel12; 33 private Random randomNumber = new Random(); RollDie2.cs
29
Sets all of the variables to 0
35 private int ones, twos, threes, fours, fives, sixes; 37 public RollDie2() { InitializeComponent(); ones = twos = threes = fours = fives = sixes = 0; } 43 // Visual Studio .NET-generated code 45 // simulates roll by calling DisplayDie for // each label and displaying the results protected void rollButton_Click( object sender, System.EventArgs e ) { // pass the labels to a method that will // randomly assign a face to each die DisplayDie( dieLabel1 ); DisplayDie( dieLabel2 ); DisplayDie( dieLabel3 ); DisplayDie( dieLabel4 ); DisplayDie( dieLabel5 ); DisplayDie( dieLabel6 ); DisplayDie( dieLabel7 ); DisplayDie( dieLabel8 ); DisplayDie( dieLabel9 ); DisplayDie( dieLabel10 ); DisplayDie( dieLabel11 ); DisplayDie( dieLabel12 ); 65 double total = ones + twos + threes + fours + fives + sixes; 67 RollDie2.cs Sets all of the variables to 0 Pass the label to be assigned a random number
30
Displays to the user the amount of times each dice number has shown up
// display the current frequency values displayTextBox.Text = "Face\t\tFrequency\tPercent\n1\t\t" + ones + "\t\t" + String.Format( "{0:F2}", ones / total * 100 ) + "%\n2\t\t" + twos + "\t\t" + String.Format( "{0:F2}", twos / total * 100 ) + "%\n3\t\t" + threes + "\t\t" + String.Format( "{0:F2}", threes / total * 100 ) + "%\n4\t\t" + fours + "\t\t" + String.Format( "{0:F2}", fours / total * 100 ) + "%\n5\t\t" + fives + "\t\t" + String.Format( "{0:F2}", fives / total * 100 ) + "%\n6\t\t" + sixes + "\t\t" + String.Format( "{0:F2}", sixes / total * 100 ) + "%"; 82 } // end rollButton_Click 84 // display the current die, and modify frequency values public void DisplayDie( Label dieLabel ) { int face = 1 + randomNumber.Next( 6 ); 89 dieLabel.Image = Image.FromFile( Directory.GetCurrentDirectory() + "\\images\\die" + face + ".gif" ); 93 Displays to the user the amount of times each dice number has shown up RollDie2.cs Assign a random face to the label based on the number generated
31
A switch statement is used to keep track of number of each die rolled
// add one to frequency of current face switch ( face ) { case 1: ones++; break; 99 case 2: twos++; break; 102 case 3: threes++; break; 105 case 4: fours++; break; 108 case 5: fives++; break; 111 case 6: sixes++; break; 114 } // end switch 116 } // end DisplayDie 118 // The main entry point for the application. [STAThread] static void Main() { Application.Run( new RollDie2() ); } 125 126 } // end of class RollDie2 A switch statement is used to keep track of number of each die rolled RollDie2.cs
32
RollDie2.cs Program Output
33
6.11 Example: Game of Chance
GUI controls A GroupBox Holds other controls Manages/organizes them A PictureBox Used to display a picture on the form
34
CrapsGame.cs 1 // Fig. 6.12: 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; 11 12 public class CrapsGame : System.Windows.Forms.Form 13 { private System.ComponentModel.Container components = null; 15 private System.Windows.Forms.PictureBox imgPointDie2; private System.Windows.Forms.PictureBox imgDie2; private System.Windows.Forms.PictureBox imgDie1; 19 private System.Windows.Forms.Label lblStatus; 21 private System.Windows.Forms.Button rollButton; private System.Windows.Forms.Button playButton; 24 private System.Windows.Forms.PictureBox imgPointDie1; 26 private System.Windows.Forms.GroupBox fraPoint; 28 // declare other variables int myPoint; int myDie1; int myDie2; 33 CrapsGame.cs
35
Creates an enumeration of the constant values in craps CrapsGame.cs
public enum DiceNames { SNAKE_EYES = 2, TREY = 3, CRAPS = 7, YO_LEVEN = 11, BOX_CARS = 12, } 42 public CrapsGame() { InitializeComponent(); } 47 // Visual Studio .NET-generated code 49 // simulate next roll and result of that roll protected void rollButton_Click( object sender, System.EventArgs e ) { int sum; sum = rollDice(); 56 if ( sum == myPoint ) { lblStatus.Text = "You Win!!!"; rollButton.Enabled = false; playButton.Enabled = true; } Creates an enumeration of the constant values in craps CrapsGame.cs When the second rolled sum equals the first rolled sum the player wins
36
If the second roll equals CRAPS (7), then the player loses
else if ( sum == ( int )DiceNames.CRAPS ) { lblStatus.Text = "Sorry. You lose."; rollButton.Enabled = false; playButton.Enabled = true; } 70 } // end rollButton_Click 72 // simulate first roll and result of that roll protected void playButton_Click( object sender, System.EventArgs e ) { int sum; myPoint = 0; fraPoint.Text = "Point"; lblStatus.Text = ""; imgPointDie1.Image = null; imgPointDie2.Image = null; 83 sum = rollDice(); 85 CrapsGame.cs If the second roll equals CRAPS (7), then the player loses
37
If on the first roll the players gets a 7 or an 11 they win
switch ( sum ) { case ( int )DiceNames.CRAPS: case ( int )DiceNames.YO_LEVEN: rollButton.Enabled = false; // disable Roll button lblStatus.Text = "You Win!!!"; break; case ( int )DiceNames.SNAKE_EYES: case ( int )DiceNames.TREY: case ( int )DiceNames.BOX_CARS: rollButton.Enabled = false; lblStatus.Text = "Sorry. You lose."; break; default: myPoint = sum; fraPoint.Text = "Point is " + sum; lblStatus.Text = "Roll Again"; displayDie( imgPointDie1, myDie1 ); displayDie( imgPointDie2, myDie2 ); playButton.Enabled = false; rollButton.Enabled = true; break; 108 } // end switch 110 } // end playButton_Click 112 private void displayDie( PictureBox imgDie, int face ) { imgDie.Image = Image.FromFile( Directory.GetCurrentDirectory() + "\\images\\die" + face + ".gif" ); } 119 CrapsGame.cs 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
38
Generates two random numbers, one for each die
// simulates the rolling of two dice private int rollDice() { int die1, die2, dieSum; Random randomNumber = new Random(); 125 die1 = randomNumber.Next( 1, 7 ); die2 = randomNumber.Next( 1, 7 ); 128 displayDie( imgDie1, die1 ); displayDie( imgDie2, die2 ); 131 myDie1 = die1; myDie2 = die2; dieSum = die1 + die2; return dieSum; 136 } // end rollDice 138 // main entry point for application [STAThread] static void Main() { Application.Run(new CrapsGame()); } 145 146 } // end of class CrapsGame CrapsGame.cs Generates two random numbers, one for each die
39
CrapsGame.cs Program Output
40
6.12 Duration of Identifiers
The amount of time an identifier exist in memory Scope The section of a program in which the object can be referenced Local variables Created when declared Destroyed when the block exits Not initialized Most variables are set to 0 All bool variables are set to false All reference variables are set to null
41
6.13 Scope Rules Scope Portion of a program in which a variable can be accessed Class scope From when created in class Until end of class (}) Global to all methods in that class Direct modification Repeated names causes previous to be hidden until scope ends Block scope From when created Until end of block (}) Only used within that block Must be passed and modified indirectly Cannot repeat variable names
42
Will output the value of 5
1 // Fig. 6.13: 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; 10 11 public class Scoping : System.Windows.Forms.Form 12 { private System.ComponentModel.Container components = null; private System.Windows.Forms.Label outputLabel; 15 public int x = 1; 17 public Scoping() { InitializeComponent(); 21 int x = 5; // variable local to constructor 23 outputLabel.Text = outputLabel.Text + "local x in method Scoping is " + x; 26 MethodA(); // MethodA has automatic local x; MethodB(); // MethodB uses instance variable x MethodA(); // MethodA creates new automatic local x MethodB(); // instance variable x retains its value 31 outputLabel.Text = outputLabel.Text + "\n\nlocal x in method Scoping is " + x; } Scoping.cs 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 5 Remains 5 despite changes to global version of x
43
Uses a new x variable that hides the value of the global x
35 // Visual Studio .NET-generated code 37 public void MethodA() { int x = 25; // initialized each time a is called 41 outputLabel.Text = outputLabel.Text + "\n\nlocal x in MethodA is " + x + " after entering MethodA"; x; outputLabel.Text = outputLabel.Text + "\nlocal x in MethodA is " + x + " before exiting MethodA"; } 50 public void MethodB() { outputLabel.Text = outputLabel.Text + "\n\ninstance variable x is " + x + " on entering MethodB"; x *= 10; outputLabel.Text = outputLabel.Text + "\ninstance varable x is " + x + " on exiting MethodB"; } 61 // main entry point for application [STAThread] static void Main() { Application.Run( new Scoping() ); } 68 69 } // end of class Scoping Scoping.cs Uses a new x variable that hides the value of the global x Uses the global version of x (1) Will permanently change the value of x globally
44
Scoping.cs Program Output
45
6.14 Recursion Recursive methods Methods that call themselves
Directly Indirectly Call others methods which call it Continually breaks problem down to simpler forms Must converge in order to end recursion Each method call remains open (unfinished) Finishes each call and then finishes itself
46
6.14 Recursion (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 Fig Recursive evaluation of 5!.
47
FactorialTest.cs 1 // Fig. 6.15: 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; 10 11 public class FactorialTest : System.Windows.Forms.Form 12 { private System.ComponentModel.Container components = null; 14 private System.Windows.Forms.Label outputLabel; 16 public FactorialTest() { InitializeComponent(); 20 for ( long i = 0; i <= 10; i++ ) outputLabel.Text += i + "! = " + Factorial( i ) + "\n"; } 25 FactorialTest.cs
48
FactorialTest.cs Program Output
// Visual Studio .NET-generated code 27 public long Factorial( long number ) { if ( number <= 1 ) // base case return 1; 32 else return number * Factorial( number - 1 ); } 36 [STAThread] static void Main() { Application.Run( new FactorialTest()); } 42 43 } // end of class FactorialTest The Factorial method calls itself (recursion) FactorialTest.cs Program Output The recursion ends when the value is less than or equal to 1
49
6.15 Example Using Recursion: The Fibonacci Sequence
F(n) = F(n - 1) + F(n - 2) Recursion is used to evaluate F(n) Complexity theory How hard computers need to work to perform algorithms
50
FibonacciTest.cs 1 // Fig. 6.16: 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; 10 11 public class FibonacciTest : System.Windows.Forms.Form 12 { private System.ComponentModel.Container components = null; 14 private System.Windows.Forms.Button calculateButton; 16 private System.Windows.Forms.TextBox inputTextBox; 18 private System.Windows.Forms.Label displayLabel; private System.Windows.Forms.Label promptLabel; 21 public FibonacciTest() { InitializeComponent(); } 26 // Visual Studio .NET-generated code 28 FibonacciTest.cs
51
The number uses the Fibonacci method to get its result
// call Fibonacci and display results protected void calculateButton_Click( object sender, System.EventArgs e ) { string numberString = ( inputTextBox.Text ); int number = System.Convert.ToInt32( numberString ); int fibonacciNumber = Fibonacci( number ); displayLabel.Text = "Fibonacci Value is " + fibonacciNumber; } 38 // calculates Fibonacci number public int Fibonacci( int number ) { if ( number == 0 || number == 1 ) return number; else return Fibonacci( number - 1 ) + Fibonacci( number - 2 ); } 47 [STAThread] static void Main() { Application.Run( new FibonacciTest() ); } 53 54 } // end of class FibonacciTest FibonacciTest.cs The number uses the Fibonacci method to get its result The recursion ends when the number is 0 or 1 Calls itself twice, to get the result of the the two previous numbers
52
FibonacciTest.cs Program Output
53
6.15 Example Using Recursion: The Fibonacci Sequence
return 1 return 0 F( 1 ) F( 0 ) F( 3 ) F( 2 ) + return Fig Set of recursive calls to method Fibonacci (abbreviated as F).
54
6.16 Recursion vs. Iteration
Uses repetition structures while, do/while, for, foreach Continues until counter fails repetition case Recursion Uses selection structures if, if/else, switch Repetition through method calls Continues until a base case is reached Creates a duplicate of the variables Can consume memory and processor speed
55
Methods with the same name
6.17 Method Overloading Methods with the same name Can have the same name but need different arguments Variables passed must be different Either in type received or order sent Usually perform the same task On different data types
56
Two versions of the square method are called
1 // Fig. 6.18: 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; 10 11 public class MethodOverload : System.Windows.Forms.Form 12 { private System.ComponentModel.Container components = null; 14 private System.Windows.Forms.Label outputLabel; 16 public MethodOverload() { InitializeComponent(); 20 // call both versions of Square outputLabel.Text = "The square of integer 7 is " + Square( 7 ) + "\nThe square of double 7.5 is " + Square ( 7.5 ); } 26 // Visual Studio .NET-generated code 28 MethodOverload.cs Two versions of the square method are called
57
MethodOverload.cs Program Output
// first version, takes one integer public int Square ( int x ) { return x * x; } 34 // second version, takes one double public double Square ( double y ) { return y * y; } 40 [STAThread] static void Main() { Application.Run( new MethodOverload() ); } 46 47 } // end of class MethodOverload One method takes an int as parameters MethodOverload.cs Program Output The other version of the method uses a double instead of an integer
58
MethodOverload2.cs Program Output
1 // Fig. 6.19: MethodOverload2.cs 2 // Overloaded methods with identical signatures and 3 // different return types. 4 5 using System; 6 7 class MethodOverload2 8 { public int Square( double x ) { return x * x; } 13 // second Square method takes same number, // order and type of arguments, error public double Square( double y ) { return y * y; } 20 // main entry point for application static void Main() { int squareValue = 2; Square( squareValue ); } 27 28 } // end of class MethodOverload2 MethodOverload2.cs Program Output 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.