You are on page 1of 65

6

Methods

Objectives
• To understand how to construct programs modularly
from small pieces called methods.
• To introduce the common math methods available in
the .NET Framework Library.
• To be able to create new methods.
• To understand the mechanisms used to pass
information between methods.
• To introduce simulation techniques using random
number generation.
• 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.
Form ever follows function.
Louis Henri Sullivan
E pluribus unum.
(One composed of many.)
Virgil
O! call back yesterday, bid time return.
William Shakespeare, Richard II
Call me Ishmael.
Herman Melville, Moby Dick
When you call me that, smile.
Owen Wister

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/24/01

260 Methods Chapter 6

Outline
6.1 Introduction
6.2 Program Modules in C#
6.3 Math Class Methods
6.4 Methods
6.5 Method Definitions
6.6 Passing Arguments: Call-by-Value vs. Call-by-Reference
6.7 Random Number Generation
6.8 Example: Game of Chance
6.9 Duration of Identifiers
6.10 Scope Rules
6.11 Recursion
6.12 Example Using Recursion: The Fibonacci Series
6.13 Recursion vs. Iteration
6.14 Method Overloading
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises

6.1 Introduction
Most computer programs that solve real-world problems are much larger than the programs
presented in the first few chapters. Experience has shown that the best way to develop and
maintain a large program is to construct it from small, simple pieces or modules. This tech-
nique is called divide and conquer. This chapter describes many key features of the C# lan-
guage that facilitate the design, implementation, operation and maintenance of large
programs.

6.2 Program Modules in C#
Modules in C# are called methods and classes. C# programs are written by combining new
methods and classes the programmer writes with “prepackaged” methods and classes avail-
able in the .NET Framework Library (also called the Base Class Library or BCL) and in
various other method and class libraries. In this chapter, we concentrate on methods; we
will discuss classes in detail beginning with Chapter 8.
The .NET Framework Library provides a rich collection of classes and methods for
performing common mathematical calculations, string manipulations, character manipula-
tions, input/output, error checking and many other useful operations. This makes the pro-
grammer’s job easier because these methods provide many of the capabilities programmers
need. The .NET Framework methods are provided as part of the .NET Framework.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/24/01

Chapter 6 Methods 261

Good Programming Practice 6.1
Familiarize yourself with the rich collection of classes and methods in the .NET Framework
and with the rich collections of classes available in various class libraries. 6.1

Software Engineering Observation 6.1
Avoid reinventing the wheel. When possible, use .NET Framework classes and methods in-
stead of writing new classes and methods. This reduces program development time and
avoids introducing new errors. 6.1

Portability Tip 6.1
Using the methods in the .NET Framework helps make programs more portable. 6.1

Performance Tip 6.1
Do not try to rewrite existing .NET Framework classes and methods to make them more ef-
ficient. You usually will not be able to increase the performance of these classes and methods.
6.1

The programmer can write methods to define specific tasks that may be used at many
points in a program. These are sometimes referred to as programmer-defined methods. The
actual statements defining the method are written only once and these statements are hidden
from other methods.
A method is invoked (i.e., made to perform its designated task) by a method call. The
method call specifies the method name and provides information (as arguments) that the
called method needs to do its task. A common analogy for this is the hierarchical form of
management. A boss (the calling method or caller) asks a worker (the called method) to
perform a task and return (i.e., report back) the results when the task is done. The boss
method does not know how the worker method performs its designated tasks. The worker
may call other worker methods and the boss will be unaware of this. We will soon see how
this “hiding” of implementation details promotes good software engineering. Figure 6.1
shows the boss method communicating with several worker methods in a hierarchical
manner. Note that worker1 acts as a “boss” method to worker4 and worker5. Rela-
tionships among methods may be other than the hierarchical structure shown in this figure.

6.3 Math Class Methods
Math class methods allow the programmer to perform certain common mathematical cal-
culations. We use various Math class methods here to introduce the concept of methods.
Throughout the book, we discuss many other methods from the classes of the .NET Frame-
work.
Methods are called by writing the name of the method followed by a left parenthesis
followed by the argument (or a comma-separated list of arguments) of the method followed
by a right parenthesis. For example, a programmer desiring to calculate and print the square
root of 900.0 might write

Console.WriteLine( Math.Sqrt( 900.0 ) );

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/24/01

7/24/01 .FromString. The preceding statement would print 30. When this statement is executed. The statement invokes the CompareTo method of the String object to which string1 refers (also referred to as sending the CompareTo message to object to which string1 refers).0. All Rights Reserved.Show). we discuss in detail the different types of methods associated with classes and how they are invoked. Software Engineering Observation 6. In Chapter 8. This statement might appear in your application’s Main method. then the statement Console. Double.2 Common Programming Error 6.0 is the argu- ment of the Math.0. 6.Sqrt is called to calculate the square root of the number contained in the parentheses (900. d = 3. The number 900.0 = 25.1 Forgetting to invoke a Math class method by preceding the method name with the class name Math and a dot operator (.0 + 3.Format and MessageBox. Note that all Math class methods must be invoked by preceding the method name with the class name Math and a dot (.CompareTo( string2 ). © Copyright 1992–2002 by Deitel & Associates.0.) results in a syntax error.1 Method arguments may be constants.0 and f = 4. The Math class is part of the System namespace which is automatically included by the com- piler. The Math.) operator. Normally.g.. Inc. calculates and prints the square root of 13.WriteLine( Math.) operator followed by a method name like the Math methods (e.2 It is not necessary to import the Math class into a program to use Math class methods. Our Main methods defined in previous examples have been called automatically or have been called using the syntax class name followed by a dot (.Sqrt( c1 + d * f ) ). namely 5.0 * 4.Sqrt method takes an argument of type double and returns a result of type dou- ble. variables or expressions.262 Methods Chapter 6 boss worker1 worker2 worker3 worker4 worker5 Fig.1 Hierarchical boss method/worker method relationship. 6.0. If c1 = 13. most methods in C# are invoked through a reference to an object as in the following line of code from an application: string1.0). 6. the method Math.Sqrt method.0. Int32.

7 ) is -12.0 ) is 30.7182818284590451 ) is 1.7182818284590451 Exp( 2. y ) x raised to power y (xy) Pow( 2.Log method).0 Pow( 9.0 ) is 128. The Math class also defines two commonly used mathe- matical constants—Math.2 ) is 10.2 Commonly used Math class methods. y ) larger value of x and y Max( 2.0 Tan( x ) trigonometric tangent of x Tan( 0.2 ) is 9.E. y ) smaller value of x and y Min( 2. the variables x and y are of type double. -12.7182818284590451) is the base value for natural logarithms (calculated with the Math.1415926535897931) of class Math is the ratio of a circle’s circumference to its diam- eter.0 ) is 7.0 not greater than x Floor( -9.38905609893065 Floor( x ) rounds x to the largest integer Floor( 9.7 (this method also has versions Max( -2.0.0 Sqrt( 9.0 ) is 1.0 (x in radians) Exp( x ) exponential method ex Exp( 1.8 ) is -10.0 Sin( x ) trigonometric sine of x Sin( 0.3.0 Cos( x ) trigonometric cosine of x Cos( 0.5 ) is 3. 7.E (2.2.7 ) is 2. Method Description Example Abs( x ) absolute value of x if x > 0 then Abs( x ) is x if x = 0 then Abs( x ) is 0 if x < 0 then Abs( x ) is -x Ceiling( x ) rounds x to the smallest integer Ceil( 9.PI and Math. 12.0 (x in radians) Sqrt( x ) square root of x Sqrt( 900.8 ) is -9.Chapter 6 Methods 263 Some Math class methods are summarized in Fig.7 for float.3 (this method also has versions Min( -2. -12. int and long val- ues) Pow( x.0 ) is 0.3. The constant Math.0 Log( x ) natural logarithm of x (base e) Log( 2. 7/24/01 . Inc. 6. int and long val- ues) Min( x.0 ) is 3.0 not less than x Ceil( -9.7 ) is -2.0 Max( x.0 (x in radians) Fig. © Copyright 1992–2002 by Deitel & Associates.PI (3.38905609893065 ) is 2.0 Log( 7.7 ) is 12. . All Rights Reserved.3 for float.0 ) is 2. 6. 12.0 ) is 0.3. In the figure.3. The constant Math.0. however many of the methods provide versions that take values of other data types as arguments.

6 using System. 5 using System. It is usually best to break such a method into several smaller methods. With good method naming and definition.NET Framework Library methods to accomplish its tasks. The divide- and-conquer approach makes program development more manageable. well-defined task. 10 11 namespace SquareIntSpace 12 { 13 /// <summary> Fig.Data. programs can be created from standardized methods rather than being built by using customized code.3: SquareInt. 6. it will become clear that several classes in the . 6.4 6. Most methods have a list of parameters that provide the means for communicating information between methods via method calls. Another motivation is software reusability—using existing methods as building blocks to create new programs. and the method name should effectively express that task.5 Method Definitions Each program we have presented has consisted of a class definition that contained at least one method definition that called . Consider a Windows application (Fig. With more programming experience. A third motivation is to avoid repeating code in a program. 264 Methods Chapter 6 6.Drawing. All Rights Reserved. A method’s parameters are also local vari- ables.3 Each method should be limited to performing a single.4 Methods Methods allow the programmer to modularize a program. 6. 6.3) that uses a method Square (invoked from the applications’s Main method) to calculate the squares of the integers from 1 to 10 1 // Fig.3 Using programmer-defined method SquareInt. 7 using System. 8 using System. 7/24/01 . it is possible that your method is attempting to perform too many diverse tasks. 3 4 using System. (part 1 of 3) © Copyright 1992–2002 by Deitel & Associates.3 Software Engineering Observation 6. Inc.4 If you cannot choose a concise name that expresses what the method does. Packaging code as a method allows that code to be executed from several locations in a program by calling the method.NET Framework contain a similar function. All variables declared in method definitions are local variables—they are known only in the method in which they are de- fined. Software Engineering Observation 6.ComponentModel. This promotes software reusability. 9 using System.Collections. we did not have to define how to convert strings to integers—such methods are already defined for us in class Convert ( ToInt32 ). For example.cs 2 // A programmer-defined Square method.Forms. We now consider how programmers write their own customized methods.Windows. There are several motivations for modularizing a program with methods. 6.

Dispose( disposing ). (part 2 of 3) © Copyright 1992–2002 by Deitel & Associates. 36 37 for ( int x = 1. 7/24/01 .Forms. 58 } 59 60 #region Windows Form Designer generated code 61 /// <summary> 62 /// Required method for Designer support .Windows. 23 24 public SquareInt() 25 { 26 // 27 // Required for Windows Form Designer support 28 // 29 InitializeComponent().Windows. 30 31 // 32 // TODO: Add any constructor code after InitializeComponent 33 // call 34 35 int result. Inc.Forms. 40 outputLabel.3 Using programmer-defined method SquareInt.Forms.Form 17 { 18 /// <summary> 19 /// Required designer variable. 22 private System.Container components = null. Chapter 6 Methods 265 14 /// Summary description for Form1. 15 /// </summary> 16 public class SquareInt : System.outputLabel = new System. All Rights Reserved. x <= 10. 47 /// </summary> 48 protected override void Dispose( bool disposing ) 49 { 50 if( disposing ) 51 { 52 if ( components != null ) 53 { 54 components.Windows.Dispose().Text += "The square of " + x + " is " + 41 result + "\n".Label outputLabel.Label().do not modify 63 /// the contents of this method with the code editor. 6. x++ ) 38 { 39 result = square( x ). 42 } 43 } 44 45 /// <summary> 46 /// Clean up any resources being used. 64 /// </summary> 65 private void InitializeComponent() 66 { 67 this. 20 /// </summary> 21 private System.ComponentModel. Fig. 55 } 56 } 57 base.

SuspendLayout().3 Using programmer-defined method SquareInt.outputLabel}). we create a label called outputLabel.ClientSize = new System.Name = "SquareInt". 80 this. 8).outputLabel. Inc.Size = new System. 81 this.Text = "SquareInt".Size(176. its Main method is called first.AddRange(new System.Location = new System. 98 } 99 100 int square( int y ) 101 { 102 return y * y. 69 // 70 // outputLabel 71 // 72 this. 13). 76 // 77 // SquareInt 78 // 79 this. 266 Methods Chapter 6 68 this.Name = "outputLabel". 73 this.Drawing. All Rights Reserved.Controls. 74 this. 6.Windows. 83 this. 92 /// </summary> 93 [STAThread] 94 95 static void Main() 96 { 97 Application.Size(192. (part 3 of 3) When the application begins execution. 85 this. 136).Forms. Every label © Copyright 1992–2002 by Deitel & Associates. 86 87 } 88 #endregion 89 90 /// <summary> 91 /// The main entry point for the application.AutoScaleBaseSize = new System.Control[] 82 {this.Drawing.outputLabel.ResumeLayout(false).outputLabel.Drawing. 7/24/01 .TabIndex = 0. 149). 75 this.Run( new SquareInt() ). As in our Win- dows application from Chapter 4. 103 } 104 105 }// end of class SquareInt 106 107 } // end of namespace SquareIntSpace Fig.Size(5.Point(8.outputLabel.Drawing. 84 this.

Chapter 6 Methods 267 contains a string property called Text. Lines 37–42 contain a for repetition structure in which each iteration of the loop calculates the Square of the current value of control variable x. You will learn more about properties in Chapter 8. 7/24/01 . which can be accessed using the same dot operator (.2 Common Programming Error 6. Method Square is invoked or called on line 39 with the statement result = Square( x ). The value returned is then assigned to variable result.) that we use to access the method in a class. is sometimes known as the method header. The method-name © Copyright 1992–2002 by Deitel & Associates. The definition of method Square (line 100) shows that Square expects an integer parameter y—this will be the name used to manipulate the value passed to Square in the body of method Square. Inc. such as public or static.2 Place a blank line between method definitions to separate the methods and enhance program readability. Line 35 declares int variable result.2 Defining a method outside the braces of a class definition is a syntax error. " is . stores the value in result and concatenates the result to the end of output.2 The format of a method definition is attributes modifiers return-value-type method-name( parameter-list ) { declarations and statements } The first line. The result is passed back to the point in SquareInt where Square was invoked. The return statement in Square passes the result of the calculation y * y back to the calling method. This process is repeated ten times using the for repetition structure. the () represent the method call operator which has high precedence. The string will be displayed on this label. This string will contain the results of squaring the values from 1–10. Lines 40–41 concatenate "The square of. All Rights Reserved." the value of result and a newline character to the end of outputLabel. Note that the entire method definition is contained between the braces of the class SquareInt. Keyword int preceding the method name indicates that Square returns an integer result." the value of x. Method square receives the copy of the value of x in the parameter y. 6. Good Programming Practice 6. In fact. The attributes and modifiers are used to specify extra information about the method. All methods must be defined inside a class definition. 6. The different attributes and modifiers will be discussed in several places throughout the book. Lines 39–41 creates a string reference output and assigns it to this Text property. a copy of the value of x (the argument to the method call) is made automatically by the program and program control transfers to the first line of method Square. Then Square calculates y * y. At this point. in which the result of each square calculation is stored. attributes modifiers return-value-type method-name( parameter-list ).Text. method Square (defined on lines 100–103) is called. When program control reaches this statement.

Common Programming Error 6. but not "hello" (because a double variable cannot con- tain a string). 7/24/01 . the parameter-list is empty (i. If a return-value-type other than void is specified. 22 or –. All Rights Reserved.5 Returning a value from a method whose return type has been declared void is a syntax er- ror. 6. A type must be listed explic- itly for each parameter in the parameter list of a method or a syntax error occurs.3 Omitting the return-value-type in a method definition is a syntax error. The method body is also referred to as a block. the method name is followed by an empty set of parentheses)..9 Good Programming Practice 6. Common Programming Error 6.6 Common Programming Error 6. The return-value-type void indicates that a method does not return a value. Methods can return at most one value.03546.7 Common Programming Error 6.3 Although it is not incorrect to do so. © Copyright 1992–2002 by Deitel & Associates.35. This helps avoid am- biguity. The return-value-type is the data type of the result returned from the method to the caller. If a method does not receive any values.4 Common Programming Error 6. 6. 6. A method cannot be defined inside another method.7 Placing a semicolon after the right parenthesis enclosing the parameter list of a method def- inition is a syntax error.268 Methods Chapter 6 is any valid identifier.4 Forgetting to return a value from a method that is supposed to return a value is a syntax er- ror. 6.5 The parameter-list is a comma-separated list containing the declarations of the param- eters received by the method when it is called. 6. a parameter of type double could receive values of 7.e.8 Common Programming Error 6. 6.9 Passing to a method an argument that is not compatible with the corresponding parameter’s type is a syntax error.8 Redefining a method parameter as a local variable in the method is a syntax error. The arguments must also be compatible with the type of the parameter. 6. y instead of float x. There must be one argument in the method call for each parameter in the method definition.6 Declaring method parameters of the same type as float x.3 Common Programming Error 6. do not use the same names for the arguments passed to a method and the corresponding parameters in the method definition. For example. A block is a compound statement that includes declara- tions.3 The declarations and statements within braces form the method body. Inc. float y is a syntax error because types are required for each parameter in the parameter list. the method must contain a return statement. 6. Variables can be declared in any block and blocks can be nested.

6. 7/24/01 . returns the value of expression to the caller. If the method does return a result. 6.1 Small methods are easier to test. Regardless of how long a method is. the statement return expression. type and order of param- eters and arguments. Inc. This makes programs easier to write. Small methods promote software reusability. © Copyright 1992–2002 by Deitel & Associates. 6.4 Choosing meaningful method names and meaningful parameter names makes programs more readable and helps avoid excessive use of comments. 6. 6. All Rights Reserved. then displays the results on the Form that is cre- ated in our program. maintain and modify.Chapter 6 Methods 269 Common Programming Error 6. 6. In this example.10 Defining a method inside another method is a syntax error. it should perform one task well.4 Software Engineering Observation 6. 6. debug.10 Good Programming Practice 6.3 actually contains four method definitions—Squa- reInt (line 1).6 Programs should be written as collections of small methods.6 Software Engineering Observation 6.5 A method should usually be no longer than one page. control returns immediately to the point at which a method was invoked. Better yet. Dispose (line 31).7 A method requiring a large number of parameters may be performing too many tasks.8 There are three ways to return control to the point at which a method was invoked. 6. almost all of the automatically generated code has been included.1 Software Engineering Observation 6. Con- sider dividing the method into smaller methods that perform the separate tasks. method Main repeatedly invokes the Square method to perform a calculation.8 The method header and method calls must all agree in the number. If the method does not return a result. InitializeComponent (line 45). Note that the example of Fig. The method header should fit on one line if possible. control is returned when the method-ending right brace is reached or by executing the statement return. Square (line 71) and Main (line 76).5 Testing and Debugging Tip 6. In this example.7 Software Engineering Observation 6. Future examples will not include methods such as Dispose and Ini- tializeComponent because the user will not alter code within those definitions. a method should usually be no longer than half a page. debug and understand than large ones. When a return statement is executed. Remember that the Main method is automatically called as it is the entry point in the application.

5 6 class MaximumValue 7 { 8 static void Main( string[] args ) 9 { 10 Console.4) uses a programmer-defined method called Maximum to determine and return the largest of three floating-point values.Write( "Enter first floating-point value: " ).Form in the last example). double y.4 Programmer-defined Maximum method. 15 16 Console.FromString( s1 ). number1. 17 string s3 = Console. 12 13 Console. The last syntax is only for static methods of a class (discussed in detail in Chapter 8).WriteLine( "\nnumber1: {0}\nnumber2: {1}" + 26 "\nnumber3: {2}\nmaximum is: {3}". Math.FromString( s2 ). Methods in the same class definition are both the methods defined in that class and the inherited methods (the methods from the class that the current class inherits from—System.4: MaximumValue. (part 1 of 2) © Copyright 1992–2002 by Deitel & Associates. number2.FromString( s3 ).ReadLine().CompareTo(string2)) and a class name followed by a method name (such as Math. 3 4 using System. number3 ).Sqrt( 9. 1 // Fig 6.Max( x. 6.Write( "Enter third floating-point value: " ).Write( "Enter second floating-point value: " ). a reference to an object followed by the dot (.Max( y. We have now seen three ways to call a method—a method name by itself (as shown with Square( x ) in this example). z ) ). 270 Methods Chapter 6 Notice the syntax used to invoke method Square—we use just the method name fol- lowed by the arguments to the method in parentheses. 22 23 double max = Maximum( number1. The application in our next example (Fig. 11 string s1 = Console. 20 double number2 = Double. 18 19 double number1 = Double.0 )). 6. Inc. number2.ReadLine().Windows. 28 } 29 30 static double Maximum( double x. double z ) 31 { 32 return Math.cs 2 // Finding the maximum of three doubles. max ). 14 string s2 = Console. 33 } 34 } Fig. 21 double number3 = Double.) operator and the method name (such as string1. 24 25 Console. Methods in a class definition are allowed to invoke all other methods in the same class definition using this syntax (there is an exception to this discussed in Chapter 8).ReadLine(). All Rights Reserved.Forms. 7/24/01 . 27 number3.

This value is returned to method Main by the return statement in method Maximum.Max is returned to the point at which Maximum was invoked (i. The three double values input by the user and the max value are concatenated and displayed to the user on lines 25–27. In many cases. the result of the second call to Math. 7/24/01 . a dou- ble converted to an int truncates the fractional part of the double value. the Math class method Sqrt can be called with an integer argument even though the method is defined in the Math class to receive a double argument and the method will still work correctly. The value returned is assigned to the variable max. y and z) to accomplish its task.e. the forcing of arguments to the appropriate type to pass to a method).3 number2: 99. correctly evaluates Math.e. Line 23 passes the three double values to method Maximum.1928 maximum is: 99.. First. Finally. The first line indicates that the method returns a double floating-point value. an int is automatically converted to a double without changing its value. Also.4 Programmer-defined Maximum method. Inc. that the method’s name is Max- imum and that the method takes three double parameters (x.Sqrt example above.Max is invoked with the values of variables y and z to determine the larger of these two values. argument values that do not correspond precisely to the parameter types in the method definition are converted to the proper type before the method is called. (part 2 of 2) The three floating-point values are input by the user via the command prompt (lines 11–17 of Main).3 Enter second floating-point value: 99. the body of the method contains the statement return Math. method Math. Notice the implementation of the method Maximum (line 30).. Next.32 number3: 27. In some cases.Max are passed to method Math.0 before the value is passed to Math.Max( x. The promotion rules specify how types can be converted to other types without losing data.32 Fig.1928 number1: 37. Converting © Copyright 1992–2002 by Deitel & Associates.Sqrt( 4 ) and prints the value 2. 6. z ) ). In our Math. All Rights Reserved. For example.WriteLine( Math. the value of variable x and the re- sult of the first call to Math. attempting these conversions leads to compiler errors if C#’s promotion rules are not satisfied. Another important feature of method definitions is the coercion of arguments (i. which returns the largest of the three floating-point values using two calls to the Math. Math.Sqrt( 4 ) ).32 Enter third floating-point value: 27.Max method.FromString to convert the strings input by the user to double values. the Main method in this program). However. The statement Console. The method definition’s pa- rameter list causes the integer value 4 to be converted to the double value 4.Max.Sqrt.Max( y. Lines 19–21 use method Double. Chapter 6 Methods 271 Enter first floating-point value: 37. which determines the largest double value.

g. This explicitly casts (converts) the value of y to an integer for use in method Square. Figure 6.5 Allowed promotions for primitive data types. object or ushort decimal object double object float double or object int decimal. double.11 Converting a primitive-data-type value to another primitive data type may change the value if the new data type is not an allowed promotion (e. int. The promotion rules apply to expressions containing values of two or more data types (also referred to as mixed-type expressions) and to primitive data type values passed as arguments to methods. float or object object None short decimal. Common Programming Error 6. not 20.5 lists the primitive data types and the types to which each is allowed to be promoted automatically. ulong or object string object Fig. int. method Square returns 16. double. long or object uint decimal. float. object.25. if y’s value is 4. Therefore. float.. long. 6. Inc. 6. uint. This promotion is also referred to as coersion of arguments. float. Also. 6. object or short char decimal. a temporary version of each value is created and used for the expres- sion—the original values remain unchanged). long.5. double. float. Thus.3) with the double variable y. double. short or ushort sbyte decimal. uint. the method call is written as Square( ( int ) y ). float. float or object ulong decimal. double. float. int. converting any integral value to a floating-point value and back to an integral value may introduce rounding errors into the result. double to int). The type of a method argument can be pro- moted to any “higher” type. which uses an integer parameter (Fig. © Copyright 1992–2002 by Deitel & Associates. ulong. long. long. long. double. long to int) may also result in changed values.272 Methods Chapter 6 large integer types to small integer types (e. All Rights Reserved. The type of each value in a mixed-type expression is promoted to the “highest” type in the expression (actually.g. double. uint.. ulong. the C# compiler requires the programmer to use a cast operator to force the conversion to occur. int. long or object ushort decimal.11 Type Allowed promotions bool object byte decimal. in cases where information may be lost due to conversion. int. double. To invoke our Square method. ulong or object long decimal. Converting values to lower types can result in different values. 7/24/01 . float. double.

9 Unlike other languages. Because arrays are treated as objects by C#. we demonstrate call-by-value and call-by-reference using arrays. and the original object can be accessed directly by the called method. In the next section.2 With call-by-value. What if the programmer would like to pass a value type by reference? To do this.2 Earlier in this book we discussed the difference between value types and reference types. Testing and Debugging Tip 6. a copy of the argument’s value is made and passed to the called method. C# does not allow the programmer to choose whether to pass each argument call-by-value or call-by-reference. a copy is returned) and objects are always re- turned by reference (i. references to objects are passed to methods. Primitive data type variables are always passed call-by-value. arrays are passed to the methods call-by- reference—a called method can access the elements of the caller’s original arrays. Objects are not passed to methods. simply specify in the method call the reference name. 7/24/01 . If arrays were passed by value. Call-by-Reference Two ways to pass arguments to methods (or functions) in many programming languages (like C and C++) are call-by-value and call-by-reference (also called pass-by-value and pass-by-reference).. primitive-data-type variables are always returned by value (i. Call-by-reference can improve performance because it can eliminate the overhead of copying large amounts of data.Chapter 6 Methods 273 6. 6.2 Passing arrays by reference makes sense for performance reasons. Software Engineering Observation 6. frequently passed arrays. Inc.9 Software Engineering Observation 6. The references themselves are also passed call-by-value. Performance Tip 6. All Rights Reserved. this would waste time and would consume considerable storage for the copies of the arrays. For large.10 To pass a reference to an object into a method. 6. At this point it is possible for the reader to understand one of the major differences between the two data types—value type variables are passed to methods using call-by- value. Mentioning the reference by its parameter name in the body of the called method actually refers to the original object in memory.e. C# pro- © Copyright 1992–2002 by Deitel & Associates.2 With call-by-reference. the method can manipulate the object directly. the caller gives the called method the ability to directly access the caller’s data and to modify that data if the called method so chooses. changes to the called method’s copy do not affect the original variable’s value in the calling method.e. The name of an array is actually a reference to an object that contains the array elements and the length instance variable. 6. which indicates the number of elements in the array.10 When returning information from a method via a return statement.. 6. whereas reference type variables are passed to methods using call-by-reference. rather. but call-by-reference can weaken security because the called method can access the caller’s data. This prevents the accidental side effects that so greatly hinder the development of correct and reliable software systems. When an argument is passed call-by-value. When a method receives a reference to an object. a copy of each element would be passed.6 Passing Arguments: Call-by-Value vs. a reference to the object is returned).

y begins uninitialized. 14 } 15 16 // x is changed and can be passed without being initialized 17 static void SquareOut( out int x ) 18 { 19 x = 6. 6.12 Although using out will suppress a syntax error for uninitialized variables. 37 38 // values of x and y are changed Fig. the compiler will generate an error.6 demonstrates the ref and out parameters to manipulate integer values. and so no error will occur. The ref parameter is used to specify that an argument being passed can be directly modified as if it were passed by reference. 21 } 22 23 // x is not changed. Doing so may make your code harder to understand. this should not always be used in place of ref. 6. 1 // Fig.cs 2 // Demonstrating ref and out parameters. 7/24/01 .Forms.\n\n\n". Common Programming Error 6. // Declare y. it is passed-by-value 24 static void Square( int x ) 25 { 26 x = x * x.6: RefOutTest. set it to 5 32 int x = 5.Windows. (part 1 of 2) © Copyright 1992–2002 by Deitel & Associates. we are specifying that we expect this variable to be initialized in the method being called. Normally when we send an uninitialized value to a method. 6. 3 4 using System. 33 int y. 20 x = x * x. on the other hand. Inc. 27 } 28 29 static void Main() 30 { 31 // Create a new integer value. 5 using System. The ref parameter is used for variables that have already been initialized. The out param- eter.6 Demonstrating ref and out parameters. 6 7 // Class used to initialize and modify an integer value 8 class RefOutTest 9 { 10 // x is changed.12 Figure 6. All Rights Reserved. but do not initialize it 34 35 string output1 = "The value of x begins as " 36 + x + ". 274 Methods Chapter 6 vides the ref parameter and the out parameter. rather than a copy of x 11 static void SquareRef( ref int x ) 12 { 13 x = x * x. By using out in place of ref. is used for values that we want initialized (and possibly modified) by the method.

simply multiplies x by itself.Information ). 49 RefOutTest. SquareRef (lines 11–14).Show( output1 + output2 + output3. The argument x is passed in as ref int. All Rights Reserved. tests SquareRef. 56 "Using ref and out Parameters". On lines 39–40 we © Copyright 1992–2002 by Deitel & Associates. The argument x is passed in as an out int. 40 RefOutTest. MessageBoxButtons. the argument passed is directly changed. We begin by initializing x to 5 and simply declaring (but not initializing) y. 7/24/01 . 54 55 MessageBox. The second method. As a result. (part 2 of 2) This program contains 3 methods to calculate the square of an integer. 6. but has not yet been initialized. rather than a copy of it being changed. does the same thing but initializes x to 6 on line 19. 50 51 string output3 = "After calling Square on both x and y. 58 59 } // end of method Main 60 61 } // end of class RefOutTest Fig. specifying that x is an integer.Square( x ). SquareOut and Square. Square (lines 24–27). 41 42 string output2 = "After calling SquareRef with x as an " + 43 "argument and SquareOut with y as an argument. 57 MessageBoxIcon. speci- fying that x is an integer being passed by reference. Chapter 6 Methods 275 39 RefOutTest. The final method.SquareOut( out y ). The first method. Method Main (lines 29–59).SquareRef( ref x ). Inc.Square( y ). " + 52 "the values of x and y are:\n\n" + 53 "x: " + x + "\n" + "y: " + y + "\n\n". and squares it’s value. simply takes x as a regular integer argument. but is being passed by reference.6 Demonstrating ref and out parameters. 46 47 // values of x and y are not changed 48 RefOutTest. SquareOut (lines 17–21).OK.\n" + 44 "the values of x and y are:\n\n" + 45 "x: " + x + "\n" + "y: " + y + "\n\n\n". and assigns the new value to x.

The Next method generates a int value that is positive. Consider the following statements: Random randomObject = new Random(). on lines 48–49 we call method Square. and y has been set to 36.276 Methods Chapter 6 call methods SquareRef and SquareOut. It is the element of chance. The range of values produced directly by Next is often different than what is needed in a specific application. Finally. entertaining diversion into a popular programming application. If Next truly produces values at random.7 Random Number Generation We now take a brief and. As the output shows. For instance. if a method calls for a ref double z. The same is true for keyword out. The program uses most of the control structures we have studied. every value in this range has an equal chance (or probability) of being chosen each time Next is called. to produce integers in the range 0 to 5. only a copy of their value is actually passed to the method. A program that randomly predicts the next type of spaceship (out of four possibilities) that will fly across the horizon in a video game would require random integers in the range 1–4.” A program that simulates rolling a six-sided die would require random integers in the range 1–6. There is something in the air of a gambling casino that invigorates people. All Rights Reserved. the values of x and y remain 25 and 36 after the calls to Square. When Next is passed one argument.13 The ref and out parameters in a method call must match those specified in the method def- inition. the double value passed as an argument must be preceded by the ref keyword. being between 0 and the maxi- mum integer value (which is different depending on the system). or a syntax error is generated. namely simulation and game playing. let us develop a program that simulates 20 rolls of a six-sided die and prints the value of each roll. The element of chance can be introduced through the Random class. the values re- turned will be in the range 0 up to (but not including) the value of the argument passed. Inc.13 6. If © Copyright 1992–2002 by Deitel & Associates. it is hoped. we will develop a nicely structured game-playing program that includes multiple methods. To demonstrate using class Random and method Next. Notice the syntax used for passing x and y— in both cases we have preceded the argument with either ref or out. the possibility that luck will convert a pocketful of money into a mountain of wealth. We use the addition operator (+) in conjunction with Next as follows: value = 1 + r.Next(). In the output we have displayed the values of x and y after the function calls. Common Programming Error 6. int randomNumber = randomObject. In this section and the next section. from the high-rollers at the plush mahogany-and-felt craps tables to the quarter-poppers at the one- armed bandits. Notice that x has been changed to 25. a program that simulates coin tossing might require only 0 for “heads” and 1 for “tails. Since x and y are both passed as regular integers. 6.Next( 6 ). For example. 7/24/01 .

27 } 28 } Fig. 7/24/01 .8: RollDie. MessageBoxIcon. i <=20. 1 // Fig. 18 output += value + " ". 12 int value.cs 2 // Generating Random integers 3 4 using System.7 Shifted random integers. 6.Forms. All Rights Reserved. Chapter 6 Methods 277 two arguments are passed to Next. 5 using System.Information ).8. the resulting value will be within a range defined by the two values passed. We then shift the range of numbers produced by adding 1 to our previous result. 19 20 if ( i % 5 == 0 ) 21 output += "\n". 22 } 23 24 MessageBox. 6. let us simulate 12 rolls of a die with the program of Fig. 6. so that the re- turn values are between 1 and 6. 6 7 class RandomInt 8 { 9 static void Main() 10 { 11 Random r = new Random(). 26 MessageBoxButtons. Inc.OK. 1 // Fig 6.Windows.Show( output.8 Rolling dice in a windows application. (part 1 of 4) © Copyright 1992–2002 by Deitel & Associates.7: RandomInt. To show that these numbers occur with approximately equal likelihood. i++ ) 16 { 17 value = 1 + r. 14 15 for ( int i = 1. The number 6 is called the scaling factor. 6. This is called scaling. rather than 0 and 5.cs 2 // Rolling 12 dice 3 Fig. 25 "20 Random Numbers from 1 to 6"\. 13 string output = "".Next( 6 ).

Windows.NET Generated Code 40 41 [STAThread] 42 43 public static void Main() 44 { 45 Application. Inc. 28 private System. (part 2 of 4) © Copyright 1992–2002 by Deitel & Associates. 55 DisplayDie( dieLabel3 ).EventArgs e) 50 { 51 // Pass the labels to a method that will randomly assign 52 // a face to each die.Forms.8 Rolling dice in a windows application. 22 private System.Data. All Rights Reserved.Forms. 7/24/01 . 9 using System.Label dieLabel12. 6 using System.ComponentModel.Windows.Forms.Forms.Windows.Windows.Forms. 19 private System.Windows. 31 private Random r = new Random().Forms.Windows.Container components = null. 53 DisplayDie( dieLabel1 ). 26 private System. 25 private System.Forms. Fig. 49 System.Label dieLabel4.Label dieLabel9. 6.Windows. 10 using System.Forms.Windows.Label dieLabel7. 16 /// </summary> 17 private System.Button rollButton.Forms.Label dieLabel5. 5 using System.Label dieLabel8.ComponentModel.Form 13 { 14 /// <summary> 15 /// Required designer variable.Windows. 37 } 38 39 // Visual Studio. 7 using System. 32 33 public RollDie() 34 { 35 // Required for Windows Form Designer support 36 InitializeComponent(). 23 private System.Forms.Drawing.Windows.Label dieLabel3. 20 private System.Windows.Label dieLabel2. 278 Methods Chapter 6 4 using System. 8 using System.Windows.Windows. 21 private System.Windows. 57 DisplayDie( dieLabel5 ).Windows.Forms. 11 12 public class RollDie : System. 18 private System. 46 } 47 48 protected void rollButton_Click (object sender.Forms.IO. 29 private System.Forms.Label dieLabel11.Run( new RollDie() ).Forms.Forms.Label dieLabel1. 27 private System.Label dieLabel10. 56 DisplayDie( dieLabel4 ). 30 private System.Label dieLabel6.Collections. 24 private System. 54 DisplayDie( dieLabel2 ).

6.Image = Image. 62 DisplayDie( dieLabel10 ). All Rights Reserved.gif" ). 60 DisplayDie( dieLabel8 ). 61 DisplayDie( dieLabel9 ). 65 } 66 67 public void DisplayDie( Label dieLabel ) 68 { 69 int face = 1 + r. 63 DisplayDie( dieLabel11 ). Chapter 6 Methods 279 58 DisplayDie( dieLabel6 ). 64 DisplayDie( dieLabel12 ).8 Rolling dice in a windows application.Next( 6 ). 7/24/01 .FromFile( 71 Directory.CurrentDirectory + "\\images\\die" + face 72 + ". Inc. 73 } 74 75 } Fig. 59 DisplayDie( dieLabel7 ). 70 dieLabel. (part 3 of 4) © Copyright 1992–2002 by Deitel & Associates.

(part 4 of 4) Until now. we gave a brief introduction to windows applications by creating some programs that display information using a label on a form. 280 Methods Chapter 6 Fig.8 Rolling dice in a windows application. Although these are valid ways to receive input from a user and display output in a C# program. they are fairly limited in their capabilities—the command prompt can obtain only one value at a time from the user and a message dialog can display only one message. It is much more common to receive multiple inputs from the user at once (such as the user © Copyright 1992–2002 by Deitel & Associates. Inc. 7/24/01 . All Rights Reserved. In Chapter 4. 6. many of our user interactions with applications have been through the com- mand prompt (in which the user could type an input value into the program) or a message dialog (which displayed a message to the user and allowed the user to click OK to dismiss the dialog).

The frequency of each face value (1 through 6) should be approximately the same. These images are placed in the proper folders on the CD that accompanies this book. The property is accessed and assigned values by using the dot operator. To begin our intro- duction to more elaborate user interfaces. and is used to specify which image will be displayed on the label. Function DisplayDie (lines 67–73) specifies the correct image based on the face value calculated on line 69. (part 1 of 5) © Copyright 1992–2002 by Deitel & Associates. the user needs to create a GUI compo- nent known as a Button." the location in which the solution is being executed. in this case a label. An event is a signal that is sent when some action takes place. they will be taken to the code for this program. 6. 6. 5 using System. 7 using System. and specifically to a method called an event handler. Whenever the user clicks on rollButton. This causes each of the 12 dice to appear as if they are being rolled again every time rollButton is clicked. When the user double-clicks on a button that they have created. Chapter 6 Methods 281 entering name and address information) or display many pieces of data at once (such as the values of the dice. 6 using System. The programmer writes the application to perform certain tasks when these events occur. When this program is created in design mode.9 to operate properly. 6.cs 2 // Rolling 12 dice with Frequency Chart 3 4 using System. Properties are members of classes that we will discuss in detail in Chapter 8. a button can simply be chosen from the ToolBox and added to our form using the drag-and-drop method. On line 70 we see the use of the Image property.9 displays how the program begins and the results after clicking Roll 10 times. Directory.Drawing. We set this value using an assign- ment statement on lines 70–72.8 to keep some simple statistics. this method will be called. Like a label. Using objects and events together allows the programmer to create applications that can interact with the user in more sophisticated ways than we have previously seen. such as a button being clicked. or a value being changed. Fig. 7/24/01 . The event handler by default will be named using the name of the object followed by an underscore and then the name of the event. 6. the sum of the dice and the point in this example). All Rights Reserved. 6.ComponentModel.9: RollDie2. 1 // Fig. There are also 12 labels that we will be using to display our dice. For now you simply need to know that a property is used to specify certain information about an object. Inc. In this case.CurrentDirectory returns the location of the folder where the current project is including "bin/Debug. This function simply calls method DisplayDie twelve times. let us modify the program of Fig.Collections.8 and Fig. the name of the method becomes rollButton_Click. 6. An event handler is a method that is executed (called) when a certain event occurs (sometimes we say an event is raised). Notice that we specify which image will be displayed by using method FromFile in class Image.9 Simulating rolling 12 six-sided dice. The die images need to be placed in this folder for the solutions in both Fig. We use this method to specify where the image is coming from. for each label. To show that these numbers occur approximately with equal likelihood. this program illustrates two new graphical user interface concepts—attaching several GUI components to an application and graphical user interface event handling. The GUI and code shown in Fig.

IO.NET generated code 42 43 protected void rollButton_Click (object sender.Windows. 56 DisplayDie( dieLabel9 ). 36 37 // TODO: Add any code after InitializeComponent call 38 ones = twos = threes = fours = fives = sixes = 0. fives.Label dieLabel7. 30 private int ones.Label dieLabel2. 29 private Random r = new Random().Windows.Label dieLabel11.Windows. 17 private System.Label dieLabel9. 27 private System. 55 DisplayDie( dieLabel8 ). 48 DisplayDie( dieLabel1 ). 15 private System. 58 DisplayDie( dieLabel11 ). 22 private System.Container components.Forms. 28 private System.Windows.Label dieLabel6.Label dieLabel1.EventArgs e) 45 { 46 // Pass the labels to a method that will randomly assign 47 // a face to each die. 39 } 40 41 // Visual Studio.Windows. Fig.Windows. 6. 52 DisplayDie( dieLabel5 ). 23 private System. twos.Windows.Forms.Forms.Forms.Windows. 20 private System.Label dieLabel8. 21 private System. 24 private System.Windows. 9 using System.Forms. fours.Windows. 54 DisplayDie( dieLabel7 ).Data.Forms. sixes. threes. 60 61 double total = ones + twos + threes + fours + fives + sixes. All Rights Reserved. 49 DisplayDie( dieLabel2 ). 26 private System. Inc.Windows.Windows.RichTextBox displayTextBox. 11 12 public class RollDie2 : System. 18 private System.Forms.Label dieLabel12.Forms.Forms.Label dieLabel3.Label dieLabel4. 57 DisplayDie( dieLabel10 ).Windows. 19 private System. 282 Methods Chapter 6 8 using System. 16 private System.ComponentModel.Forms. 44 System.9 Simulating rolling 12 six-sided dice.Button rollButton. 50 DisplayDie( dieLabel3 ). 7/24/01 .Forms. 59 DisplayDie( dieLabel12 ). 25 private System.Windows. 10 using System. 31 32 public RollDie2() 33 { 34 // Required for Windows Form Designer support 35 InitializeComponent().Windows.Forms.Label dieLabel5.Forms.Windows.Forms.Label dieLabel10.Form 13 { 14 private System.Forms. 51 DisplayDie( dieLabel4 ). (part 2 of 5) © Copyright 1992–2002 by Deitel & Associates. 53 DisplayDie( dieLabel6 ).Forms.

00" ) + 68 "%\n3\t\t" + threes + "\t" + 69 double. (part 3 of 5) © Copyright 1992–2002 by Deitel & Associates. 84 85 switch ( face ) 86 { 87 case 1: ones++.Format( twos / total * 100.00" ) + 66 "%\n2\t\t" + twos + "\t" + 67 double.Format( fours / total * 100. 92 break. 96 break. 90 break. 7/24/01 .00" ) + 74 "%\n6\t\t" + sixes + "\t" + 75 double. 91 case 3: threes++.Text = "Frequency\tFace\tPercent\n1\t\t" + 64 ones + "\t" + 65 double.Image = Image. Inc.Format( ones / total * 100.Next( 6 ). "0. 93 case 4: fours++. 76 } 77 78 public void DisplayDie( Label dieLabel ) 79 { 80 int face = 1 + r. 105 } 106 } Fig. "0. 89 case 2: twos++. "0. Chapter 6 Methods 283 62 63 displayTextBox. 97 case 6: sixes++.Format( fives / total * 100.gif" ). 99 } 100 } 101 102 public static void Main() 103 { 104 Application. All Rights Reserved.CurrentDirectory + "\\images\\die" + face + 83 ". "0.00" ) + 70 "%\n4\t\t" + fours + "\t" + 71 double. 6.Run( new RollDie2() ). 98 break.00" ) + 72 "%\n5\t\t" + fives + "\t" + 73 double.FromFile( 82 Directory.00" ) + "%".Format( threes / total * 100.Format( sixes / total * 100. "0.9 Simulating rolling 12 six-sided dice. 94 break. 81 dieLabel. 88 break. "0. 95 case 5: fives++.

Inc. 6. 7/24/01 . All Rights Reserved.9 Simulating rolling 12 six-sided dice. (part 4 of 5) © Copyright 1992–2002 by Deitel & Associates. 284 Methods Chapter 6 Fig.

over a large number of die rolls.Next( 6 ). which always assigns an integer (at random) to variable face in the range 1 ≤ face ≤ 6. The values produced directly by Next are always in the range 0 ≤ r. Notice that a different sequence of random numbers is obtained each time the program is executed. Note that no default case is provided in the switch structure. the number of consecutive integers in the range) is 6 and the starting number in the range is 1. by scaling and shifting we have utilized function Next to realistically simulate the rolling of a six-sided die (i.. Referring to the preceding statement. so the program results should vary. each of the six possible faces from 1 through 6 appears with equal likelihood about one sixth of the time). (part 5 of 5) As the program output shows.9 Simulating rolling 12 six-sided dice.e.1 ) Previously we demonstrated how to write a single statement to simulate the rolling of a six- sided die with the statement face = 1 + r. 6. we see that © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved.. Chapter 6 Methods 285 Fig.Next( x ) < ( x . After we study arrays in Chapter 7. Note that the width of this range (i. 7/24/01 . Run the program several times and observe the results. Inc. we will show how to replace the entire switch structure in this program with a single-line statement.e.

PictureBox imgPointDie1. 10 using System.10 simulates the game of craps. 8 using System.e.PictureBox imgPointDie2. 21 private System.Windows.Windows. 20 private System.Forms.ComponentModel. 6.10 Program to simulate the game of craps. Notice that the player must roll two dice on the first and all subsequent rolls. 7/24/01 .” which is played in casinos and back alleys throughout the world..IO.Button rollButton. 17 private System. The rules of the game are straightforward: A player rolls two dice.ComponentModel.Label lblStatus. the sum of the spots on the two upward faces is calculated. The application in Fig. 9 using System. 6. roll your point value). All Rights Reserved.Forms. Fig. 2.e. 6) and the starting number of the range is equal to the number (i.Button playButton.Collections.Forms. you must con- tinue rolling the dice until you “make your point” (i. respectively.Drawing.Windows.Next( 6 ). where a is the shifting value (which is equal to the first number in the desired range of con- secutive integers) and b is the scaling factor (which is equal to the width of the desired range of consecutive integers).. 286 Methods Chapter 6 the width of the range is determined by the Next argument (i. 5 and 6 spots. 6. If the sum is 4. We can generalize this result as follows: n = a + r. 7 using System. 1) added to r. 1 // Fig 6. the player loses (i. 3 or 12 on the first throw (called “craps”). 6.e. The form displays the results of each roll..Forms. click the Play button to play the game.Forms. 6 using System. 18 private System. that sum becomes the player’s “point. Each die has six faces.Next( b ).PictureBox imgDie2. If the sum is 2. After the dice have come to rest.Windows.Windows.Forms.” To win.Data. 19 private System.cs 2 // Craps Game 3 4 using System. 16 private System..8 Example: Game of Chance One of the most popular games of chance is a dice game known as “craps. 5.e. (part 1 of 6) © Copyright 1992–2002 by Deitel & Associates. the “house” wins).Form 13 { 14 private System.Forms.Forms.Windows. 15 private System. Inc. 5 using System.10: CrapsGame. the player wins.Container components = null. 11 12 public class CrapsGame : System.PictureBox imgDie1. 4. The player loses by rolling a 7 before making the point.Windows.Windows.Forms. 8. 3. 9 or 10 on the first throw. If the sum is 7 or 11 on the first throw. The screen captures show the execution of a single game.Windows. When you execute the application. These faces contain 1.

51 sum = rollDice(). 57 playButton.Enabled = true. 52 53 if ( sum == myPoint ) 54 { 55 lblStatus. 64 playButton. Fig. 73 fraPoint.Text = "Point". 26 int myDie1. 56 rollButton. 41 } 42 43 // Visual Studio. 32 trey = 3. 34 boxCars = 12.Enabled = true. 27 int myDie2. 35 } 36 37 public CrapsGame() 38 { 39 // Required for Windows Form Designer support 40 InitializeComponent().GroupBox fraPoint.EventArgs e ) 70 { 71 int sum.Windows.Enabled = false. 58 } 59 else 60 if ( sum == 7 ) 61 { 62 lblStatus. Chapter 6 Methods 287 22 private System. 33 yoLeven = 11. 69 System.Enabled = false. 75 imgPointDie1.10 Program to simulate the game of craps. 28 29 public enum DiceNames 30 { 31 snakeEyes = 2.".Forms. 6. 65 } 66 } 67 68 protected void playButton_Click ( object sender. 63 rollButton.Image = null. 23 24 //declare other variables 25 int myPoint.Text = "". 48 System.Text = "Sorry.EventArgs e) 49 { 50 int sum. 74 lblStatus. 7/24/01 . Inc. (part 2 of 6) © Copyright 1992–2002 by Deitel & Associates. 72 myPoint = 0.NET generated code 44 45 [STAThread] 46 47 protected void rollButton_Click (object sender. You lose.Text = "You Win!!!". All Rights Reserved.

Image = Image. 79 80 switch ( sum ) 81 { 82 case 7: 83 case ( int )DiceNames. 99 playButton. 127 } 128 129 public static void Main() Fig.Enabled = true. dieSum. 110 } 111 112 private int rollDice() 113 { 114 int die1. 100 rollButton. 7/24/01 . die2 ).yoLeven: 84 rollButton.Next( 6 ). 126 return dieSum. 96 lblStatus.".snakeEyes: 88 case (int)DiceNames.Enabled = false.Enabled = false. You lose. 92 break. 95 fraPoint. 98 displayDie( imgPointDie2. 97 displayDie( imgPointDie1. (part 3 of 6) © Copyright 1992–2002 by Deitel & Associates. 125 dieSum = die1 + die2.Text = "Sorry. 115 Random r = new Random().CurrentDirectory + "\\images\\die" + face + 109 ".trey: 89 case (int)DiceNames. 6. 93 default: 94 myPoint = sum.Image = null. 124 myDie2 = die2. die2. myDie2 ).gif" ).Next( 6 ). 102 } 103 } 104 105 private void displayDie( PictureBox imgDie. int face ) 106 { 107 imgDie.boxCars: 90 rollButton. 118 die2 = 1 + r.10 Program to simulate the game of craps.Text = "You Win!!!". 116 117 die1 = 1 + r. 119 120 displayDie( imgDie1.FromFile( 108 Directory. All Rights Reserved. // Disable Roll button 85 lblStatus. myDie1 ).Text = "Point is " + sum. Inc. 101 break. 87 case (int)DiceNames. 288 Methods Chapter 6 76 imgPointDie2. 121 displayDie( imgDie2. 86 break. 91 lblStatus.Enabled = false.Text = "Roll Again". 122 123 myDie1 = die1. 77 78 sum = rollDice(). die1 ).

All Rights Reserved. 132 } 133 } Fig. 7/24/01 . Inc. 6.Run( new CrapsGame() ).10 Program to simulate the game of craps. Chapter 6 Methods 289 130 { 131 Application. (part 4 of 6) © Copyright 1992–2002 by Deitel & Associates.

290 Methods Chapter 6 Fig. 7/24/01 . Inc. 6.10 Program to simulate the game of craps. (part 5 of 6) © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved.

The next line spec- © Copyright 1992–2002 by Deitel & Associates. (part 6 of 6) Lines 4–10 specify to the compiler where to locate the classes used in this application. Chapter 6 Methods 291 Fig. This namespace gives the programmer the ability to include various graphics in their program (see Chapter 16). classes Random and Double). All Rights Reserved.10 Program to simulate the game of craps. The second using statement includes all the classes in the System. Inc.Drawing namespace. 6. but will not be used yet. 7/24/01 . The first using statement specifies that the program uses classes from namespace System (specifically. Many of these namespaces are included automatically.

Forms. Within the GroupBox we add two PictureBoxes. the reader will see several declarations.NET generated code. All Rights Reserved. 7/24/01 . Because we have used the identifiers snakeEyes. The fifth using state- ment specifies that the program uses classes from namespace System. is used display the user’s point. In this program we have introduced a few new components. This method is also defined in the automatically generated code.Collections.Form.Win- dows. Method playButton_Click is used for the beginning of the game. In this program. The first component. Before any method definitions. type.rollButton_Click is the event handler for the event rollButton. This namespace contains many data types that enable a program to process a user’s interactions with a program’s GUI.Click. Depending on the value of the users roll. it is specified that the method this.Windows.IO. usually representing data structures (see Chapter 24). the but- tons rollButton and PlayButton will either become disabled or enabled. we use the classes Pic- tureBox. which dis- plays the dice and returns their sum.Data and System.Forms. A GroupBox is used as a container for other components. Line 51 calls method rollDice (defined on lines 112–127). including our first enumeration on lines 29–35. components used to display images. called a GroupBox. The switch statement on lines 80–102 will analyze this roll similarly to the if/else structure in method rollButton_Click. 6.9 Duration of Identifiers Chapters 2–5 used identifiers for variable names and reference names. This class allows us to include collections of objects. which enable database work and input and output from files or streams (Chapter 17 and Chapter 19). Inc. We also use identifiers as © Copyright 1992–2002 by Deitel & Associates. Remember that all forms inherit from class System. the program itself reads closer to English and less like several numbers and symbols. The last using statements include the namespaces System.Form.292 Methods Chapter 6 ifies the namespace System. which is set to true or false. These are added in the same way as before. Label.Windows. This is done using the Enabled property. Line 12 indicates that class CrapsGame inherits from System. This method’s task is to process a user’s interaction with the rollButton (called Roll Dice on the user interface) in this example. and can help aid in the management of these components. by clicking on PictureBox in the ToolBox and then dragging this component within the borders of the GroupBox. This enumeration is used for reference throughout the program. The attributes of variables and references include name. An enumeration is a data type that contains several con- stant values. size and value. yoLeven and boxCars. letting the user know if they won or lost. Every C# program is based on at least one class definition that extends and enhances an existing class definition via inheritance. When the user clicks the Play button.Forms. and is created using the keyword enum. this method will declare and initialize certain values (lines 71–76) and execute the opening roll of the game (line 78).Forms. The rest of rollButton_Click analyzes the roll.Win- dows. In the Visual Studio. Button and GroupBox from namespace System. trey. A class can inherit existing attributes and behaviors (data and methods) from another class specified to the right of operator : in the class definition.

they exist while the block in which they are declared is active and they are destroyed when the block in which they are declared is exited. Duration and scope (where a name can be used) are separate issues. 7/24/01 .e.11 Automatic duration is a means of conserving memory because automatic duration variables are created when program control reaches their declaration and are destroyed when the block in which they are declared is exited.10 Scope Rules The scope (sometimes called a declaration space) of an identifier for a variable. this does not mean that these iden- tifiers can be used throughout the program.Chapter 6 Methods 293 names for user-defined methods and classes. This section discusses duration of identifiers.11 The instance variables of a class are automatically initialized by the compiler if the programmer does not provide initial values.3 Automatic variables must be initialized before they are used in a method. 6.. Software Engineering Observation 6. Variables and references of static duration exist from the point at which the class that defines them is loaded into memory for execu- tion until the program terminates. Some identifiers can be referenced throughout a program. Section 6. 6. parameters and variables declared in the method body) have automatic duration. Actually. All Rights Reserved. An identifier’s duration (also called its lifetime) is the period during which that iden- tifier exists in memory.3 C# also has identifiers of static duration. while others can be referenced from only limited portions of a program. Variables of most primitive data types are ini- tialized to zero and bool variables are initialized to false. References are initialized to null. automatic variables must be initialized by the programmer before they can be used. © Copyright 1992–2002 by Deitel & Associates. For the remainder of the text. Some identifiers exist briefly. the com- piler issues an error message. Testing and Debugging Tip 6. otherwise. some are repeatedly created and destroyed and others exist for the entire execution of a program. reference or method is the portion of the program in which the identifier can be referenced. including duration and scope. Automatic duration variables are created when program control reaches their declaration.10 discusses the scope of identifiers. “Control Structures: Part II”). There is also a special scope—method scope (label declaration space)—for labels used with the break and continue statements (introduced in Chapter 5. each identifier in a program has oth- er attributes. as discussed in the next section. Even though the static duration variable and reference names exist when their classes are loaded into memory. Inc. Labels are only visible in the block in which they are declared. A local variable or reference declared in a block can be used only in that block or in blocks nested within that block. we will refer to variables of automatic duration as automatic variables or local variables. 6. Their storage is allocated and initialized when their classes are loaded into memory. The scopes for an identifier are class scope and block scope. Unlike instance variables of a class. An identifier’s scope is where the identifier can be referenced in a program. Identifiers that represent local variables in a method (i.

In Chapter 8.12 The program of Fig. 10 11 public class Scoping : System. }. Identifiers declared inside a block have block scope (local variable declaration space).Collections.Data.Drawing.5 Avoid local variable names that hide instance variable names. 7 using System. This helps prevent accidental and/or malicious errors from occurring in systems. All Rights Reserved. 5 using System. and are visible in what is known as the declara- tion space of a class. {.ComponentModel. 294 Methods Chapter 6 Members of a class have class scope.12 Automatic duration is an example of the principle of least privilege. With for structures. 6. (part 1 of 3) © Copyright 1992–2002 by Deitel & Associates. This can be accomplished by avoiding the use of duplicate identifiers in a class. Fig. In a sense. Good Programming Practice 6. When blocks are nested in a method’s body and an identifier declared in an outer block has the same name as an identifier declared in an inner block.cs 2 // A Scoping example. all instance variables and methods of a class are global to the method of the class in which they are defined (i..11: Scoping.11 A scoping example.11 demonstrates scoping issues with instance variables and local variables. of the class definition. the value in the outer block is “hidden” until the block terminates execution. 6. Any block may contain variable or reference decla- rations. the methods can modify the instance variables directly and invoke other methods of the class). Class scope begins at the opening left brace.Forms. any variable declared in the ini- tialization portion of the for header will only be visible within that for structure. 8 using System. Inc. 14 private System.Windows.Forms.ComponentModel.Forms. 3 4 using System.Windows. Class scope enables methods of a class to directly invoke all members defined in that same class or inherited into that class.Label outputLabel. In Chapter 8. 9 using System.5 Software Engineering Observation 6. Why have variables stored in memory and ac- cessible when they are not needed? 6. The reader should note that block scope applies also to methods and for structures. which are also local variables of the method. 6. 6. of the class definition and terminates at the closing right brace. but no additional rights or privileges. we discuss how to access such “hidden” instance variables. 1 // Fig. 7/24/01 . we will see that static members are an exception to this rule.Form 12 { 13 private System.Windows.e. 6 using System. This principle states that each component of a system should have sufficient rights and privileges to accomplish its designated task. The same occurs if a local variable in a method has the same name as an instance variable. Block scope begins at the identifier’s declaration and ends at the terminating right brace (}) of the block.Container components = null. Local variables of a method have block scope as do method parameters.

21 int x = 5.Text = outputLabel.Run( new Scoping() ).Text = outputLabel.Text + 53 "\n\ninstance variable x is " + x + 54 " on entering MethodB".Text = outputLabel.Text = outputLabel.11 A scoping example. 44 ++x. 17 18 public Scoping() 19 { 20 InitializeComponent(). 59 } 60 61 public static void Main() 62 { 63 Application. Chapter 6 Methods 295 15 16 public int x = 1.Text + 57 "\ninstance varable x is " + x + 58 " on exiting MethodB". Inc. 25 26 MethodA().NET generated code 36 37 public void MethodA() 38 { 39 int x = 25. 45 outputLabel. // initialized each time a is called 40 41 outputLabel. 6. 7/24/01 .Text + 42 "\n\nlocal x in MethodA is " + x + 43 " after entering MethodA".Text + 24 "local x in start is " + x.Text = outputLabel. 56 outputLabel.Text + 32 "\n\nlocal x in start is " + x.Text = outputLabel. // MethodB uses instance variable x 28 MethodA(). // MethodA has automatic local x. (part 2 of 3) © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved. // variable local to constructor 22 23 outputLabel.Text + 46 "\nlocal x in MethodA is " + x + 47 " before exiting MethodA". 48 } 49 50 public void MethodB() 51 { 52 outputLabel. // MethodA reinitializes automatic local x 29 MethodB(). // instance variable x retains its value 30 31 outputLabel. 27 MethodB(). 64 } 65 } Fig. 33 } 34 35 // Visual Studio. 55 x *= 10.

the program displays the local variable x in Scoping again to show that none of the method calls modified the value of x because the methods all referred to variables in other scopes. incremented and displayed again before exiting the method. Therefore. the method returns a result. If the method is called with a base case. Each method is called twice from method Scoping. when it refers to vari- able x. When MethodB is called. Method MethodA defines variable x (line 52) and initializes it to 25. A recursive method is called to solve a problem. We consider recursion conceptually first. Method Scoping declares a local variable x (line 20) and initializes it to 5. Recursive problem-solving approaches have a number of elements in common. This book contains an extensive treatment of recursion. 10. multiplied by 10 and displayed again before exiting the method. then examine several programs containing recursive methods. A recursive method is a method that calls itself either directly or indirectly through another method. The method actually knows how to solve only the simplest case(s) or so-called base case(s).11 Recursion The programs we have discussed are generally structured as methods that call one another in a disciplined. In this section and the next. the instance variable has its modified value. This instance variable is hidden in any block (or method) that declares a variable named x. simple examples of recursion are presented. 6. Method MethodB does not declare any variables. the instance variable is displayed in outputLabel. Inc. If the method is called with a more complex problem. 6. (part 3 of 3) Instance variable x (line 15) is declared and initialized to 1. The program defines two other methods—MethodA and MethodB—that each take no arguments and return nothing. 296 Methods Chapter 6 Fig. automatic variable x is recreated and initialized to 25. All Rights Reserved. Each time this method is called. The next time method MethodB is called. Finally. Recursion is an important topic discussed at length in upper-level computer science courses.11 A scoping example. 7/24/01 . This variable is displayed in the outputLabel to show that the instance variable x is hidden in Scoping. For some problems. the variable is displayed in outputLabel. the instance variable x is used. hierarchical manner. When MethodA is called. it is useful to have methods call themselves. the method divides the problem into two conceptual pieces: a piece that the method knows © Copyright 1992–2002 by Deitel & Associates.

At that point.12b shows the values returned from each recursive call to its caller until the final value is calculated and returned. the method recognizes the base case. which terminates the recursion.12a shows how the succession of recursive calls proceeds until 1! is evaluated to be 1. As an example of these concepts at work. The factorial of a nonnegative integer n. as is shown by the following: 5! = 5 · 4 · 3 · 2 · 1 5! = 5 · ( 4 · 3 · 2 · 1 ) 5! = 5 · ( 4! ) The evaluation of 5! would proceed as shown in Fig. The recursion step can result in many more recursive calls. 7/24/01 . counter >= 1. returns a result to the previous copy of the method and a sequence of returns ensues up the line until the original method call eventually returns the final result to the caller. counter-. All Rights Reserved.1 ) · ( n . which is equal to 120. This sounds exotic compared to the con- ventional problem solving we performed to this point. The recursion step executes while the original call to the method is still open (i. can be calculated iter- atively (nonrecursively) using for as follows: factorial = 1. written n! (and pronounced “n factorial”). let us write a recursive program to perform a popular mathematical calculation. the latter piece must resemble the original problem. 5! is the product 5 · 4 · 3 · 2 · 1.1)! For example. For the recursion to eventually terminate. the sequence of smaller and smaller problems must converge on the base case. each time the method calls itself with a slightly simpler version of the original problem. Inc.12. To make recur- sion feasible. For example. is the product n · ( n . the method invokes (calls) a fresh copy of itself to go to work on the smaller problem—this is referred to as a recursive call and is also called the recursion step. it has not finished executing).e. 6. number. Figure 6.) factorial *= counter. The factorial of an integer. The recursion step also normally includes the keyword return because its result will be combined with the portion of the problem the method knew how to solve to form a result that will be passed back to the original caller. Figure 6.. Because this new problem looks like the original problem. A recursive definition of the factorial method is arrived at by observing the following relationship: n! = n · (n . 5! is clearly equal to 5 * 4!. © Copyright 1992–2002 by Deitel & Associates.Chapter 6 Methods 297 how to do (base case) and a piece that the method does not know how to do. for ( int counter = number. as the method divides each new subproblem into two conceptual pieces. greater than or equal to 0. but be a slightly simpler or slightly smaller version of the original problem.2 ) · … · 1 with 1! equal to 1 and 0! defined to be 1.

Windows. no further recursion is necessary and the method returns.. 6. 7/24/01 .1.ComponentModel.Text += i + "! = " + Fig. line 45 return number * Factorial( number . 298 Methods Chapter 6 Final value = 120 5! 5! 5! = 5 * 24 = 120 is returned 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 2 * 1! 1 returned 1 1 (a) Procession of recursive calls.1 ).Forms. 6. 9 10 public class FactorialTest : System.13: FactorialTest. 8 using System. Figure 6. If number is greater than 1. 18 19 for ( long i = 0. (b) Values returned from each recursive call.e. 3 4 using System. 6 using System. 13 private System. 5 using System.13 Calculating factorials with a recursive method.Windows.Forms. Fig.Windows.Collections. The recursive method Fac- torial first tests to see if a terminating condition is true (i. (part 1 of 2) © Copyright 1992–2002 by Deitel & Associates.Drawing. If number is indeed less than or equal to 1. factorial returns 1. All Rights Reserved.Forms.cs 2 // Recursive factorial method. expresses the problem as the product of number and a recursive call to Factorial eval- uating the factorial of number . i++ ) 20 outputLabel.Form 11 { 12 private System.Label outputLabel. Inc.1 ) is a slightly simpler problem than the original calculation Factorial( number ). 1 // Fig 6.12 Recursive evaluation of 5!. 7 using System. is number less than or equal to 1).Container components = null. Note that Factorial( number . 14 15 public FactorialTest() 16 { 17 InitializeComponent().ComponentModel. i <= 10.13 uses recursion to calculate and print the factorials of the integers 0–10 (the choice of the data type long will be explained momentarily).

7/24/01 .Run( new FactorialTest() ).13 Calculating factorials with a recursive method. This points to a weakness in most programming languages. 6. 32 } 33 34 public static void Main() 35 { 36 Application. We chose data type long so the program can calculate factorials greater than 20! Unfortunately. 30 else 31 return number * Factorial( number . 6. Common Programming Error 6.15 © Copyright 1992–2002 by Deitel & Associates. Inc. All Rights Reserved. namely that the languages are not easily extended to handle the unique requirements of various applications. 6.14 Common Programming Error 6. Chapter 6 Methods 299 21 Factorial( i ) + "\n". eventually exhausting memory. (part 2 of 2) Method Factorial (line 40) receives a parameter of type long and returns a result of type long.13. the Factorial method produces large values so quickly that even long does not help us print many factorial values before the size of a long variable is exceeded. This is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution. 6.14 Forgetting to return a value from a recursive method when one is needed results in a syntax error.1 ). As can be seen in Fig.15 Either omitting the base case or writing the recursion step incorrectly so that it does not con- verge on the base case will cause infinite recursion. 22 } 23 24 // Visual Studio. factorial values become large quickly. 37 } 38 } Fig.NET generated code 25 26 public long Factorial( long number ) 27 { 28 if ( number <= 1 ) // base case 29 return 1. We explore in the exercises that float and double may ultimately be needed by the user desiring to calculate factorials of larger numbers.

ComponentModel. Remember.e. The application of Fig. Automatically. All Rights Reserved. 3 4 using System. the this keyword enables the application to refer to itself. Fig.Drawing.14. © Copyright 1992–2002 by Deitel & Associates. repeatedly occurs in nature and has been called the golden ratio or the golden mean.618…. … begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers. a message is sent to the application (i. Method calculateButton_Click executes automatically in response to the user interface event and calls recursive method Fibonacci to calculate the specified Fibonacci number. 1. 6 using System.14 calculates the ith Fi- bonacci number recursively using method Fibonacci.. 300 Methods Chapter 6 6.14 Recursively generating Fibonacci numbers. The Fibonacci series may be defined recursively as follows: Fibonacci( 0 ) = 0 Fibonacci( 1 ) = 1 Fibonacci( n ) = Fibonacci( n – 1 ) + Fibonacci( n – 2 ) Note that there are two base cases for the Fibonacci calculation—fibonacci(0) is defined to be 0 and fibonacci(1) is defined to be 1. The series occurs in nature and. 6. 6. Inc. 13. 5 using System. 8. rooms and buildings whose length and width are in the ratio of the golden mean. The event handling in this example is similar to the event handling of the Craps appli- cation in Fig. The ratio of successive Fibonacci numbers converges on a constant value of 1. The user enters an integer in the first textfield indicating the ith Fibonacci number to calculate and clicks the calculate- Button (which displays the text Calculate Fibonacci) button. Postcards are often designed with a golden mean length/width ratio. the screen captures show the results of calculating several Fibonacci numbers. method InitializeComponent of this application creates the GUI components and attaches them to the application’s form.cs 2 // Recursive fibonacci method. 1 // Fig 6. 7/24/01 . a method—calculateButton_Click—is called on the application indicating that the user of the program interacted with one of the program’s GUI components (calculate- Button). Therefore.10. 3. too.14: FibonacciTest. 7 using System. Once again.Collections.12 Example Using Recursion: The Fibonacci Series The Fibonacci series 0. In Fig. 1. 6. describes a form of spiral. 21. In this example. 2. in particular. Humans tend to find the golden mean aesthetically pleasing. the user clicks calculateButton while typing in inputTextBox to generate the action event. Notice that Fibonacci numbers tend to become large quickly. This number. Remember that this button will not cause any action to execute if an event han- dler for this action is not defined. we use data type long for the parameter type and the return type in method Fibonacci. Architects often design win- dows. 5. 6.

17 private System.ComponentModel. 15 private System. Chapter 6 Methods 301 8 using System.Forms.Windows.Run( new FibonacciTest() ).Container components. 35 } 36 37 public static void Main() 38 { 39 Application.1 ) + Fibonacci( number .Windows. 14 private System.EventArgs e) 23 { 24 int number = Int32. 7/24/01 . 18 19 // Visual Studio. © Copyright 1992–2002 by Deitel & Associates.14 Recursively generating Fibonacci numbers.Windows.Forms. 25 int fibonacciNumber = Fibonacci( number ). 6.2 ). 9 10 11 public class FibonacciTest : System.Windows.Windows.Form 12 { 13 private System.Forms. 16 private System. 26 displayLabel. Inc.Label promptLabel.Forms. 33 else 34 return Fibonacci( number .Forms.TextBox inputTextBox.NET generated code 20 21 protected void calculateButton_Click (object sender. 40 } 41 42 } Fig. 22 System.Label displayLabel.Text ).Text = "Fibonacci Value is " + fibonacciNumber. All Rights Reserved.Button calculateButton.Windows.Forms. 27 } 28 29 public int Fibonacci( int number ) 30 { 31 if ( number == 0 || number == 1 ) 32 return number.FromString( inputTextBox.

namely the order dictated by the rules of operator prece- dence. This is a different issue from the order in which opera- tors are applied to their operands. © Copyright 1992–2002 by Deitel & Associates. it immediately tests for the base case—number equal to 0 or 1 (line 71). From Fig.15 shows how method Fibonacci would evaluate Fibonacci(3)—we abbreviate Fibonacci as F to make the figure more readable. number is returned (fibonacci(0) is 0 and fibonacci(1) is 1). If this is true. but all subsequent calls to Fibonacci are recursive. The C and C++ languages (on which many of C#’s features are based) do not specify the order in which the operands of most operators (including +) are evaluated.15 it appears that while evaluating F(3). namely F(2) and F(1). each of which is for a slightly simpler problem than the original call to Fibonacci. 6. This figure raises some interesting issues about the order in which C# compilers will evaluate the operands of operators.14 Recursively generating Fibonacci numbers. Therefore. 7/24/01 . if number is greater than 1. 6. All Rights Reserved. Each time Fibonacci is invoked. The call to Fibonacci (line 65) from calculateButton_Click is not a recur- sive call. the recursion step generates two recursive calls. In C# this is true. But in what order will these calls be made? Most program- mers assume the operands will be evaluated left to right. two recursive calls will be made. Figure 6. Interestingly. 302 Methods Chapter 6 Fig. Inc.

The calls could in fact execute F(2) first. you will notice that each consecutive Fibonacci number you ask the applet to calculate results in a substantial increase in calculation time and number of calls to the Fibonacci method. modify and maintain. 0 or 1) results in two more recursive calls to the Fibonacci method.692. or the calls could exe- cute in the reverse order: F(1). Thus. the number of calls to Fibonacci is increasing quickly—1. the method calls are in fact F(2) first.080 additional calls between Fibonacci of 30 and 31 and 2. then F(1).15 Set of recursive calls to method fibonacci. 7/24/01 . then F(2). All Rights Reserved. debug.5 times the difference for Fibonacci of 30 and 31.537 calls to the Fibonacci method. This rapidly gets out of hand. 6.e. A word of caution is in order about recursive programs like the one we use here to gen- erate Fibonacci numbers.692. 6. Complexity issues are discussed in detail in the upper-level computer science curriculum course generally called “Algorithms.155 calls.049.” © Copyright 1992–2002 by Deitel & Associates. it turns out the final result would be the same. For example. Good Programming Practice 6. But in some programs the evaluation of an operand may have side effects that could affect the final result of the expression. As you can see. Each invocation of the Fibonacci method that does not match one of the base cases (i.617 calls and the Fibonacci value of 32 requires 7. In this program and in most other programs.664.. calculating the Fibonacci value of 30 requires 2. 6. then F(1). This difference in number of calls made between Fibonacci of 31 and 32 is more than 1.6 F( 3 ) return F( 2 ) + F( 1 ) return F( 1 ) + F( 0 ) return 1 return 1 return 0 Fig.538 additional calls between Fibonacci of 31 and 32.891 calls to the Fibonacci method. As you try larger values.356. This often results in programs that are difficult to read. Problems of this nature humble even the world’s most powerful computers! Computer scientists study in the field of complexity theory how hard algorithms have to work to do their jobs.Chapter 6 Methods 303 the programmer can make no assumption in those languages about the order in which these calls execute.14 requires 21. Calculating the Fibonacci value of 20 using the pro- gram in Fig. Inc. The C# language specifies that the order of evaluation of the operands is left to right.6 Do not write expressions that depend on the order of evaluation of the operands of an oper- ator. the Fibonacci value of 31 requires 4.

13 Recursion vs. Recursive calls take time and consume ad- ditional memory.16 Accidentally having a nonrecursive method call itself either directly or indirectly through an- other method can cause infinite recursion. recursion uses a selection structure (such as if. So why choose recursion? Software Engineering Observation 6. so the overhead of repeated method calls and extra memory assignment is omitted. Iteration In the previous sections. recursion terminates when a base case is recognized. Both iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false.4 Avoid using recursion in performance situations. It repeatedly invokes the mechanism. Recursion has many negatives. this can consume considerable memory. In this section we compare the two approaches and discuss why the programmer might choose one approach over the other in a particular situation. Both iteration and recursion involve repetition: Iteration explicitly uses a repetition structure. infinite recursion occurs if the recursion step does not reduce the problem each time in a manner that converges on the base case. Iter- ation with counter-controlled repetition and recursion each gradually approach termination: Iteration keeps modifying a counter until the counter assumes a value that makes the loop- continuation condition fail. recursion achieves repetition through repeated method calls. 6. of method calls. Another reason to choose a recursive solution is that an iterative solution may not be apparent. only the method’s variables) to be created. Both iteration and recursion are based on a control structure: Iteration uses a repetition structure (such as for. Iteration normally occurs within a method.13 Any problem that can be solved recursively can also be solved iteratively (nonrecursively). Inc. This can be expensive in both processor time and memory space. Each recursive call causes another copy of the method (actually. 6. and consequently the overhead. we studied two methods that can easily be implemented either re- cursively or iteratively. 7/24/01 . while or do/while). We feel that recursion is a sufficiently rich and complex topic that it is better to introduce it earlier and spread the examples over the remainder of the text. 6.304 Methods Chapter 6 Performance Tip 6.4 Common Programming Error 6. if/else or switch).16 Most programming textbooks introduce recursion much later than we have done here.3 Avoid Fibonacci-style recursive programs. © Copyright 1992–2002 by Deitel & Associates. 6. recursion keeps producing simpler versions of the original problem until the base case is reached. which result in an exponential “explosion” of calls.3 6. A recursive approach is normally chosen in preference to an iterative approach when the re- cursive approach more naturally mirrors the problem and results in a program that is easier to understand and debug. All Rights Reserved. Iteration and recursion each involve a termination test: Iteration terminates when the loop-continuation condition fails.13 Performance Tip 6.

Inc. one-piece) program without methods—makes potentially large numbers of method calls and these consume exe- cution time and space on a computer’s processor(s). C# executes a “best-fit” algorithm for matching the method being called. types and order of the arguments in the call. hierarchical manner promotes good software engineering. Overloaded methods are distinguished by their signature—a combination of the method’s name and its parameter types. debug. the types of the parameters and the order of the parameters). Good software engineering is important. Good software engineering is key to making more manageable the task of developing larger and more complex software sys- tems. When an overloaded method is called. Method overloading is commonly used to cre- ate several methods with the same name that perform similar tasks.e. test. 6. Unfortunately. If the C# compiler only looked at method names during compilation. the types of each parameter. 6. maintain and evolve. All Rights Reserved. which will place ever greater computing demands on hardware. But monolithic programs are difficult to program. 7/24/01 .14 Method Overloading C# enables several methods of the same name to be defined as long as these methods have different sets of parameters (based on the number of parameters.7 Figure 6. the code in Fig.. always keeping in mind the delicate balance between performance and good software engineering.Chapter 6 Methods 305 Let us reconsider some observations we make repeatedly throughout the book. High performance is often important.5 A heavily modularized program—as compared to a monolithic (i. This is called method overloading.7 Overloading methods that perform closely related tasks can make programs more readable and understandable. 6. But it has a price. the C# compiler selects the proper method by examining the number. but on different data types.16 would be ambiguous—the compiler would not know how to distinguish the two Square methods. Where do methods fit in here? Software Engineering Observation 6. Good Programming Practice 6. the exact order of the parameters and the return type to determine if the methods in a class are unique in that class.14 Performance Tip 6.14 Modularizing programs in a neat. If first searches for all the methods that can be used in this context.16 uses overloaded method Square to calculate the square of an int and the square of a double. It © Copyright 1992–2002 by Deitel & Associates. 6.5 So modularize your programs judiciously. 6. these goals are often at odds with one another. High performance in these systems is key to realizing the systems of the future. the compiler uses longer “mangled” or “decorated” names that include the original method name. Logically.

16 17 public MethodOverload() 18 { 19 InitializeComponent().Label outputLabel.17: MethodOverload. © Copyright 1992–2002 by Deitel & Associates.ComponentModel.Form 12 { 13 14 private System. 8 using System. 20 21 outputLabel. 40 } 41 } Fig. 306 Methods Chapter 6 may seem that only one method would match.16 Using overloaded methods.Run( new MethodOverload() ).5 is " + Square ( 7. 31 } 32 33 public double Square ( double y ) 34 { 35 return y * y.Forms.Forms.Forms.Windows. 1 // Fig 6. but remember that C# will execute implicit conversions on variables. 6. 6 using System. Once all of these methods are found.Text = 22 "The square of integer 7 is " + Square( 7 ) + 23 "\nThe square of double 7.Container components = null.Drawing. 5 using System. 9 10 11 public class MethodOverload : System.Windows.NET generated code 27 28 public int Square ( int x ) 29 { 30 return x * x. 3 4 using System. 24 } 25 26 // Visual Studio.cs 2 // Using overloaded methods. 36 } 37 public static void Main() 38 { 39 Application. Inc.ComponentModel.Windows. 7/24/01 .Collections. All Rights Reserved. the closest match is chosen.5 ). 7 using System. 15 private System.

4 5 using System.” If the parameters are speci- fied as follows: void Foo( float a.cs 2 // Overloaded methods with identical signatures and 3 // different return types. 6. So far.17 illustrates the compiler errors generated when two methods have the same signature and different return types. in Fig. the compiler might use the logical name “square of int” for the Square method that specifies an int parameter and “square of double” for the Square method that specifies a double parameter.17 1 // Fig. The preceding two Foo methods are considered to be distinct by the compiler. Fig. The program of Fig. but must have different parameter lists. Overloaded methods can have different return types. 17 } 18 19 static void Main() 20 { 21 int squareValue = 2. int b ) the compiler might use the logical name “foo of float and int.16. This is because methods cannot be distinguished by return type. 6. 7/24/01 . overloaded methods need not have the same number of parameters. Chapter 6 Methods 307 For example. 22 Square( squareValue ). 6. If a method Foo’s definition begins as follows: void Foo( int a. Also. float b ) the compiler might use the logical name “foo of int and float. the logical names of methods used by the compiler did not mention the return types of the methods. Inc.17 Creating overloaded methods with identical parameter lists and different return types is a syntax error. 6 7 public class MethodOverload2 8 { 9 public int Square( double x ) 10 { 11 return x * x. 6.” Note that the order of the parameters is important to the compiler.17 Compiler error messages generated from overloaded methods with identical parameter lists and different return types.18: MethodOverload2. Common Programming Error 6. All Rights Reserved. © Copyright 1992–2002 by Deitel & Associates. 6. 12 } 13 14 public double Square( double y ) 15 { 16 return y * y.

308 Methods Chapter 6

23 }
24 }

Fig. 6.17 Compiler error messages generated from overloaded methods with
identical parameter lists and different return types.

SUMMARY
• The best way to develop and maintain a large program is to construct it from small, simple pieces
or modules. This technique is called divide and conquer.
• Modules in C# are called methods and classes.
• C# programs are written by combining new methods and classes the programmer writes with “pre-
packaged” methods and classes available in the .NET Framework Library and in various other
method and class libraries.
• The .NET Framework Library provides a rich collection of classes and methods for performing
common mathematical calculations, string manipulations, character manipulations, input/output,
error checking and many other useful operations.
• The programmer can write methods to define specific tasks that may be used at many points in a
program. These are sometimes referred to as programmer-defined methods.
• The actual statements defining the method are written only once and these statements are hidden
from other methods.
• Methods are called by writing the name of the method (sometimes preceded by the class name and
a dot operator) followed by a left parenthesis followed by the argument (or a comma-separated list
of arguments) of the method followed by a right parenthesis.
• All variables declared in method definitions are local variables—they are known only in the meth-
od in which they are defined.
• Packaging code as a method allows that code to be executed from several locations in a program
by calling the method.
• The return statement in a method is used to pass the results of the method back to the main pro-
gram.
• The format of a method definition is

attributes modifiers return-value-type method-name( parame-
ter-list )
{
declarations and statements
}

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/24/01

Chapter 6 Methods 309

• The first line of a method definition is sometimes known as the method header. The attributes and
modifiers in the method header are used to specify extra information about the method.
• The return-value-type is the data type of the result returned from the method to the caller. Methods
can return at most one value.
• The parameter-list is a comma-separated list containing the declarations of the parameters re-
ceived by the method when it is called. There must be one argument in the method call for each
parameter in the method definition.
• The declarations and statements within the braces after the method header form the method body.
• Variables can be declared in any block and blocks can be nested.
• A method cannot be defined inside another method.
• Methods in the same class definition are both the methods defined in that class and the inherited
methods.
• In many cases, argument values that do not correspond precisely to the parameter types in the
method definition are converted to the proper type before the method is called.
• When an argument is passed call-by-value, a copy of the argument’s value is made and passed to
the called method.
• With call-by-reference, the caller gives the called method the ability to directly access the caller’s
data and to modify that data if the called method so chooses.
• The class Random can be used to generate random numbers which are often used in applications.
• An event is a signal that is sent when some action takes place, such as a button being clicked, or a
value being changed. The programmer writes the application to perform certain tasks when these
events occur. An event handler is a method that is executed (called) when a certain event occurs
(sometimes we say an event is raised).
• A class can inherit existing attributes and behaviors (data and methods) from another class speci-
fied to the right of operator : in the class definition.
• An identifier’s duration (also called its lifetime) is the period during which that identifier exists in
memory.
• Identifiers that represent local variables in a method (i.e., parameters and variables declared in the
method body) have automatic duration. Automatic duration variables are created when program
control reaches their declaration, they exist while the block in which they are declared is active
and they are destroyed when the block in which they are declared is exited.
• The scope (sometimes called a declaration space) of an identifier for a variable, reference or meth-
od is the portion of the program in which the identifier can be referenced.
• A local variable or reference declared in a block can be used only in that block or in blocks nested
within that block.
• Members of a class have class scope, and are visible in what is known as the declaration space of
a class.
• Class scope enables methods of a class to directly invoke all members defined in that same class
or inherited into that class (static members are an exception to this rule).
• Any variable declared in the initialization portion of the for header will only be visible within
that for structure.
• A recursive method is one that calls itself either directly or indirectly through another method.
• A recursive method actually knows how to solve only the simplest case(s) or so-called base
case(s). If the method is called with a base case, the method returns a result. If the method is called

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/24/01

310 Methods Chapter 6

with a more complex problem, the method divides the problem into two conceptual pieces: a piece
that the method knows how to do (base case) and a piece that the method does not know how to do.
• To make recursion feasible, the portion of the problem that the method does not know how to do
must resemble the original problem, but be a slightly simpler or slightly smaller version of the
original problem.
• Certain recursive functions can lead to exponential "explosive" calls that the compiler or computer
cannot handle.
• Both iteration and recursion are based on a control structure: Iteration uses a repetition structure
(such as for, while or do/while); recursion uses a selection structure (such as if, if/else
or switch).
• Both iteration and recursion involve repetition: Iteration explicitly uses a repetition structure; re-
cursion achieves repetition through repeated method calls.
• Iteration and recursion each involve a termination test: Iteration terminates when the loop-contin-
uation condition fails; recursion terminates when a base case is recognized.
• Both iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-
continuation test never becomes false; infinite recursion occurs if the recursion step does not re-
duce the problem each time in a manner that converges on the base case.
• A recursive approach is normally chosen in preference to an iterative approach when the recursive
approach more naturally mirrors the problem and results in a program that is easier to understand
and debug.
• C# enables several methods of the same name to be defined as long as these methods have different
sets of parameters (based on the number of parameters, the types of the parameters and the order
of the parameters). This is called method overloading.
• Method overloading is commonly used to create several methods with the same name that perform
similar tasks, but on different data types.
• C# executes a “best-fit” algorithm for matching the method being called.

TERMINOLOGY
. (dot operator)
argument to a method call
array
attribute
automatic duration
automatic initialization of a variable
base case(s)
block scope
Button class
call-by-reference
call-by-value
calling method
cast operator
class
class scope
Click event
coercion of arguments
comma-separated list of arguments
complexity theory

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/24/01

All Rights Reserved.Chapter 6 Methods 311 computer-assisted instruction (CAI) concatenate constant variable continue statement control structures in iteration control structures in recursion convergence declaration divide-and-conquer approach duration of an identifier event handling exhausting memory exponential “explosion” of calls factorial method Fibonacci series defined recursively golden ratio hierarchical structure infinite loop infinite recursion inheritance instance variables of a class interface invoke iteration lifetime of an identifier local variable method method body method call method overloading mixed-type expression modifier modularizing a program with methods monolithic program named constant nested block nested control structure null out parameter overloaded method parameter list precedence principle of least privilege programmer-defined method promotions for primitive data types Random class read-only variable recursive evaluation recursive method ref parameter © Copyright 1992–2002 by Deitel & Associates. 7/24/01 . Inc.

This is called method ________. o) Recursion is based on a control structure: it uses a ________ structure. i) Variables declared in a block or in a method’s parameter list are of ________ duration. n) Iteration is based on a control structure: it uses a ________ structure. 7/24/01 . l) In C#. © Copyright 1992–2002 by Deitel & Associates. s) Recursion terminates when a ________ is reached. d) The ________ statement in a called method can be used to pass the value of an expres- sion back to the calling method. t) Placing a semicolon after the right parenthesis enclosing the parameter list of a method definition is a ________ error. b) A method is invoked with a ________.1 Answer each of the following: a) Program modules in C# are called ________ and________. it is possible to have various methods with the same name that each operate on different types and/or numbers of arguments. q) The best way to develop and maintain a large program is to divide it into several smaller program ________ each of which is more manageable than the original program. m) Local variables declared at the beginning of a method have ________ scope.312 Methods Chapter 6 return keyword return-value-type scaling factor scope of an identifier sequence of random numbers shifting value side effect signature simulation single-line statement software reusability stack static duration termination test user interface event void return-value-type SELF-REVIEW EXERCISES 6. Inc. p) Recursion achieves repetition through repeated ________ calls. f) The ________ of an identifier is the portion of the program in which the identifier can be used. All Rights Reserved. j) A method that calls itself either directly or indirectly is a ________ method. k) A recursive method typically has two components: one that provides a means for the re- cursion to terminate by testing for a ________ case and one that expresses the problem as a recursive call for a slightly simpler problem than the original call. e) The keyword ________ is used in a method header to indicate that a method does not return a value. as do method parameters which are considered local variables of the method. ________ and ________. h) The method is used to produce random numbers. g) The three ways to return control from a called method to a caller are ________. c) A variable known only within the method in which it is defined is called a ________. r) It is possible to define methods with the same ________ but different parameter lists.

floating-point result.2 actually produce the indicated results. x <= 10. ex. c) The method cube. explain why. for ( x = 1. k) A recursive implementation of the Fibonacci method is always efficient. l) Any problem that can be solved recursively can also be solved iteratively. g) When a method recursively calls itself it is known as the base case. If false. } } 6. e) The line Application.WriteLine( x ). public class CubeTest { int x. All Rights Reserved. d) Variable type char cannot be promoted to type int. a) Math method Abs rounds its parameter to the smallest integer. e) The variable yPos. j) Infinite recursion occurs when a method converges on the base case. h) 0! Is equal to 1. floating-point arguments side1 and side2 and returns a double-precision. state the scope (either class scope or block scope) of each of the following elements.Chapter 6 Methods 313 u) The ________ is a comma-separated list containing the declarations of the parameters received by the method when it is called. w) A ________ is a signal that is sent when some action takes place. a) Method hypotenuse. a) The variable x. 6. c) Variable type float can be promoted to type double.2 State whether each of the following is true or false. 6.4 Write an application that tests if the examples of the math library method calls shown in Figure 6. } } public int cube( int y ) { return y * y * y. b) The variable y. which takes two double-precision. public void paint() { int yPos = 25. 6. Inc.3 For the following program. © Copyright 1992–2002 by Deitel & Associates.Run appears at least once in every C# windows application. i) Forgetting to return a value from a recursive method when one is needed results in a syn- tax error. 7/24/01 . b) Math method Exp is the exponential method.5 Give the method header for each of the following methods. f) A recursive method is one that calls itself. yPos += 15. x++ ) { Console. v) The ________ is the data type of the result returned from the method to the called. d) The method paint. such as a button being clicked or a value being changed.

c) Local variable. i) Automatic. h) True i) True j) False. 6. l) True 6. t) Syntax.] d) Method intToFloat.2 a) False. result. which takes three integers. and double. [Note: Such methods are commonly used to display instructions to a user. b) True c) True d) False. c = 4. result = a * b * c. float. e) void.WriteLine( "Inside method g" ). else n + sum( n . } ANSWERS TO SELF-REVIEW EXERCISES 6. k) Base. Recursion repeatedly invokes the mechanism.1 a) Methods and classes. r) Name. l) Overloading. Console. f) Scope.Next. m) Block . d) return. } h) void f( float a ). b = 5. b) Block scope. } g) int sum( int n ) { if ( n == 0 ) return 0. z and returns an integer. which does not take any arguments and does not return a val- ue. Infinite recursion will occur when a recursive method does not converge on the base case.314 Methods Chapter 6 b) Method smallest. All Rights Reserved. q) Modules . s) Base case. c) Method instructions. h) Ran- dom.1 ). j) Recursive.WriteLine( "Inside method h" ). of method calls. 6. which takes an integer argument. } } f) int sum( int x. d) Class scope. long. e) True f) True g) False. p) Method. return result. { float a. 7/24/01 . Console. v) Return-value- type. or encountering the closing right brace of a method. result = x + y. u) Parameter list. x. b) Method call.4 The following code demonstrates the use of some Math library method calls: © Copyright 1992–2002 by Deitel & Associates.WriteLine( "Result is " + result ). k) False. w) event.6 Find the error in each of the following program segments and explain how the error can be corrected: e) int g() { Console.WriteLine( a ). 6. o) Se- lection. c) Class scope. When a method recursively calls itself it is known as the recursive call or recursion step. y. n) Repetition. or return expression.3 a) Class scope. Inc. Type char can be promoted to int. number and returns a float- ing-point result. int h() { Console. g) return. Math method Abs returns the absolute value of a number. int y ) { int result. and consequently the overhead. e) Block scope. } i) void product() { int a = 6.

389056 ) ).7 ) = " + 8 Math.Min( -2.Cos( 0.WriteLine( "Math.Abs( -23. Chapter 6 Methods 315 1 // Exercise 6. 33 Console.0 ) ).Pow( 9. 7/24/01 . -12.7 ) = " + 36 Math. 7 ) ).7 ) ).Max( -2.2 ) ).Sin( 0. 12.Min( 2. 27 Console.Sqrt( 25.Log( 2.Exp( 2. 49 } 50 } © Copyright 1992–2002 by Deitel & Associates. 41 Console.389056 ) = " + 30 Math.5 ) ).7 ) ).0 ) ).Max( -2.Sqrt( 25.Ceiling( -9.Sin( 0.3.Max( 2.0 ) = " + 44 Math.Pow( 2. 31 Console.0 ) = " + 20 Math.Min( 2.Tan( 0.Exp( 1.7 ) ).3. . 21 Console. -12.Ceiling( 9.WriteLine( "Math. 9 Console.7 ) ).0 ) = " + 10 Math.Log( 7.WriteLine( "Math. 45 Console.3.7 ) = " + 38 Math.Exp( 1.Floor( -9. 29 Console.Ceiling( 9. 23 Console. 11 Console.8 ) ).7 ) = " + 12 Math.0 ) ).Log( 2.Pow( 2.8 ) = " + 26 Math.0 ) = " + 46 Math.WriteLine( "Math.Abs( 0. 25 Console. 17 Console. 19 Console. 47 Console.WriteLine( "Math.8 ) = " + 16 Math.0 ) = " + 22 Math.WriteLine( "Math.WriteLine( "Math. 12.WriteLine( "Math.cs 2 // Testing the Math class methods 3 4 public class MathTest { 5 public static void Main( String [] args ) 6 { 7 Console.WriteLine( "Math.3.0 ) ).Max( 2.Abs( 23.3.Pow( 9.Cos( 0.718282 ) = " + 28 Math.Log( 7.WriteLine( "Math. 15 Console.Tan( 0.7 ) ).3. All Rights Reserved.WriteLine( "Math.WriteLine( "Math.5 ) = " + 42 Math.2 ) = " + 14 Math.Floor( -9.0 ) = " + 48 Math.Exp( 2.718282 ) ). 13 Console. -12.3.Abs( -23.Floor( 9. 39 Console.3.WriteLine( "Math.Abs( 23.WriteLine( "Math.0 ) ).Min( -2. Inc.0 ) ). 37 Console.WriteLine( "Math.Ceiling( -9.WriteLine( "Math.7 ) = v + 32 Math.WriteLine( "Math. 35 Console.WriteLine( "Math.Abs( 0.0 ) = " + 18 Math. 43 Console.2 ) ).0 ) ).WriteLine( "Math.WriteLine( "Math. 12. -12. 7 ) = " + 40 Math.7 ) = " + 34 Math.2 ) = " + 24 Math. 12.3: MathTest.7 ) ).WriteLine( "Math.Floor( 9. .8 ) ).

int y.3.Abs( 0.Tan( 0. 12.0 ) = 7.Abs( 23. Correction: Change the return type to int.7 ) = 12.38906 Math.Exp( 2.5 ) = 3 Math. int z ) c) void instructions() d) float intToFloat( int number ) 6. b) Error: The method is supposed to return an integer.7 ) = 2.3 Math.Floor( 9.6 a) Error: Method h is defined in method g. 7/24/01 .Floor( -9.3. -12.Sin( 0. Correction: Delete variable result and place the following statement in the method: return x + y. d) Error: The semicolon after the right parenthesis that encloses the parameter list and re- defining the parameter a in the method definition are each incorrect.1) is not returned by this recursive method. Inc. All Rights Reserved.3.7 Math.3. double side2 ) b) int smallest( int x.71828 Math.7 What is the value of x after each of the following statements is performed? a) x = Math.Abs( 0.Sqrt( 25.Min( 2.1).7 ) = 23.5 a) double hypotenuse( double side1.Ceiling( 9. c) Error: The result of n + sum(n .. 7 ) = 128 Math. but does not.Cos( 0. EXERCISES 6.389056 ) = 2 Math.Ceiling( -9.0 ) = 0 Math.3 Math.8 ) = -9 Math.Floor( 7.Log( 2.7 ) = -12.Max( -2. e) Error: The method returns a value when it is not supposed to.0 ) = 0 6.2 ) = 10 Math. -12. .Min( -2.0 ) = 2.2 ) = 9 Math.316 Methods Chapter 6 Math. Correction: Rewrite the statement in the else clause as return n + sum(n . resulting in a syntax error.0 ) = 0 Math.0 ). or add the following statement at the end of the method body: return result.Log( 7.7 Math.718282 ) = 1 Math.Max( 2.5 ).Abs( -23.8 ) = -10 Math. c) x = Math.Exp( 1.0 ) = 5 Math. 12.7 Math.Abs( 7.7 Math. Correction: Delete the semicolon after the right parenthesis of the parameter list and de- lete the declaration float a. b) x = Math. Correction: Move the definition of h out of the definition of g.5 ).Pow( 9.0 ) = 1 Math.7 ) = 23.Pow( 2.7 ) = -2. © Copyright 1992–2002 by Deitel & Associates.

0 ). 6. Assume that no car parks for longer than 24 hours at a time. Do not use any Math library methods. Incorporate this method into an applet that reads integer values for side1 and side2 from TextBoxs and performs the calculation with the hypotenuse meth- od.00 minimum fee to park for up to three hours. f) x = Math.00. 6. 6.0 4. Method integerPower should use for or while to control the calculation. Note that this method should gather data from Textboxes and should print to a label.Abs( -6. e) x = Math. Assume that exponent is a positive. nonzero integer and base is an integer. The method should take two arguments of type double and return the hypotenuse as a double. if side is 4. Incorporate this method into an applet that reads integer values from TextBoxs for base and exponent from the user and performs the calculation with the integerPower method.0 2 5. All Rights Reserved.Chapter 6 Methods 317 d) x = Math. The max- imum charge for any given 24-hour period is $10.0 15. Write a program that calculates and displays the parking charges for each customer who parked a car in this garage yesterday. this method should print © Copyright 1992–2002 by Deitel & Associates.Ceiling( -6.18 to form the square out of whatever character is contained in character parameter fillCharacter. Determine the length of the hypotenuse for each of the following triangles.18 6.Ceiling( -Math. 6.Abs( -8 + Math. For example. The program should use the method calculateCharges to determine the charge for each customer.11 Write a method squareOfAsterisks that displays a solid square of asterisks whose side is specified in integer parameter side. Use the techniques described in the chapter to read the double value from a TextBox. You should enter in a TextBox the hours parked for each customer. 4 ) = 3 * 3 * 3 * 3.12 Modify the method created in Exercise 6. the method displays **** **** **** **** Incorporate this method into an application that reads an integer value for side from the user at the keyboard and performs the drawing with the squareOfAsterisks method.4 ). The garage charges an additional $0. 6. integerPower( 3. Thus if side is 5 and fillCharacter is “#”.0 3 8. exponent ) that returns the value of base exponent For example. Inc.0 12.0 Fig. The program should display the charge for the current customer.50 per hour for each hour or part thereof in excess of three hours. g) x = Math.10 Define a method hypotenuse that calculates the length of the hypotenuse of a right trian- gle when the other two sides are given. 7/24/01 .4 ).5 ) ) ). Triangle Side 1 Side 2 1 3.8 A parking garage charges a $2.9 Write a method integerPower( base.Ceiling( 0.Floor( -5.

each side of the coin should appear approximately half the time. Allow the user to enter the number of disks in a TextBox.15 (Towers of Hanoi) Every budding computer scientist must grapple with certain classic prob- lems and the Towers of Hanoi (Fig. using peg 1 as a temporary holding area.e. if we attack the problem with recursion in mind. The program should call a separate method flip that takes no arguments and returns false for tails and true for heads. draw the string "No. A separate method should be used to generate each new question. the base case). We wish to develop an algorithm that will print the precise sequence of peg-to-peg disk transfers.13 Write an application that simulates coin tossing. we would rapidly find our- selves hopelessly knotted up in managing the disks. Instead. 6. Display the results. This is accomplished by trivially moving the disk without the need for a temporary holding area. Let the program toss the coin each time the user presses the “Toss” button. it immediately becomes tractable. then ask another multiplica- tion question. using peg 3 as a temporary holding area. Supposedly. It should then display a question in the status bar such as How much is 6 times 7? The student then types the answer into a TextBox.14 Computers are playing an increasing role in education. c) Move the n – 1 disks from peg 2 to peg 3. This method should be called once when the applet begins execution and each time the user answers the question correctly. A third peg is available for temporarily holding disks. priests are attempting to move a stack of disks from one peg to another. the world will end when the priests complete their task. All Rights Reserved. Use the Next method from an object of type Random to produce two positive one-digit integers.. The process ends when the last task involves moving n = 1 disk (i. then let the student try the same question again repeatedly until the student finally gets it right. draw the string "Very good!" in a read-only TextBox.] 6. Let us assume that the priests are attempting to move the disks from peg 1 to peg 3. Please try again. The priests are attempting to move the stack from this peg to a second peg under the constraints that exactly one disk is moved at a time and at no time may a larger disk be placed above a smaller disk. Your program checks the student's answer. Write an applet to solve the Towers of Hanoi problem. Inc.318 Methods Chapter 6 ##### ##### ##### ##### ##### 6. so there is little incentive for us to facilitate their efforts. If we were to approach this problem with conventional methods. The initial stack had 64 disks threaded onto one peg and arranged from bottom to top by decreasing size.19) is one of the most famous of these. [Note: If the program realistically simulates the coin tossing." in the same read-only TextBox. 7/24/01 . Write a program that will help an el- ementary school student learn multiplication. Count the number of times each side of the coin appears. b) Move the last disk (the largest) from peg 1 to peg 3. Use a recursive tower method with four parameters: a) The number of disks to be moved b) The peg on which these disks are initially threaded c) The peg to which this stack of disks is to be moved d) The peg to be used as a temporary holding area © Copyright 1992–2002 by Deitel & Associates. Legend has it that in a temple in the Far East. 6. If it is correct. If the answer is wrong. Moving n disks can be viewed in terms of moving only n – 1 disks (and hence the recursion) as follows: a) Move n – 1 disks from peg 1 to peg 2.

Write a recursive method gcd that returns the greatest common divisor of x and y.28. y ) is x.Chapter 6 Methods 319 Your program should display in a read-only TextBox with scrolling functionality the precise instructions it will take to move the disks from the starting peg to the destination peg. then gcd( x. The gcd of x and y is defined recursively as follows: If y is equal to 0.19 The Towers of Hanoi for the case with four disks. All Rights Reserved. gcd( x. x % y ).16 The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. your program should print the following series of moves: Fig. y ) is gcd( y. For example. 6. 1 → 3 (This means move one disk from peg 1 to peg 3.) 1→2 3→2 1→3 2→1 2→3 1→3 6. to move a stack of three disks from peg 1 to peg 3. Inc. © Copyright 1992–2002 by Deitel & Associates. 7/24/01 . Use this method to replace the one you wrote in the applet of Exercise 6. where % is the modulus operator. otherwise.

7/24/01 . • Please feel free to send any lengthy additional comments by e-mail to cheryl. • Please be constructive. Please send us a short e-mail if you would like to make such a suggestion. Comments: • Please mark your comments in place on a paper copy of the chapter. • Please do not rewrite the manuscript. please show us how to correct it. © Copyright 1992–2002 by Deitel & Associates.Chapter 6 Methods 327 [***Notes To Reviewers***] Questions: • Is "coercion of terms" an actual phrase in C#? • We are unsure if this sentence is true for C#: The type of each value in a mixed-type expression is promoted to the “highest” type in the expression (actually. a temporary version of each value is created and used for the expression—the original values remain unchanged). Inc.net. We will not make significant adjustments to our writing style on a global scale. • Please check that we are using the correct programming idioms. We are concerned mostly with technical correctness and cor- rect use of idiom. That person will probably find most typos. • Please review the index we provide with each chapter to be sure we have covered the topics you feel are important.yaeger@dei- tel. errors or omissions in the chapter discussions. spelling errors. etc. • Please run all the code examples. • The manuscript is being copyedited by a professional copy editor in parallel with your reviews. This book will be published soon. line-by-line comments. Inc. All Rights Reserved. We all want to publish the best possible book. • Please check that there are no inconsistencies. • Please read all of the back matter including the exercises and any solutions we provide. grammatical errors. • Please do not send us e-mails with detailed. mark these directly on the pa- per pages. • Please return only marked pages to Deitel & Associates. • If you find something that is incorrect.

cs 306 B converting an integral value to a MethodOverload2. 286 Double.cs 281 declaration 267 Rolling dice in a windows Demonstrating ref and out C parameters. 274 automatic duration 293 concatenate 267 FactorialTest.cs 286 argument to a method call 267 (CAI) 324 Demonstrating ref and out attribute 267 computers in education 324 parameters. 281 calling method 261 double promotions 272 Using overloaded methods. 263 Commonly used Math class Allowed promotions for primitive Compiler error messages methods. 264 Shifted random integers. casino 276. 307 argument 261. 298 algorithm 303 methods. 277 called method 261 dot (.cs base case(s) 296. 307 generated from overloaded area of a circle 326 complexity theory 303 methods. 263 data types. initialized 293 control structures in iteration 304 262 control structures in recursion 304 MaximumValue. 272 generated from overloaded Compiler error messages application’s form 300 methods. 294 A scoping example.Index 1 Symbols class scope 293 equal likelihood 277 . bool variables initialized to craps table 276 298 false 293 CrapsGame.Format method 262 306 cast operator 272 Double.cs 294 recursive method.cs 286 Recursively generating braces ({ and }) 267 Fibonacci numbers.cs 277 bool promotions 272 craps program 326 Recursive evaluation of 5!. 274 application. 302. All Rights Reserved. 272 absolute value 263 arguments 261 Calculating factorials with a ActionEvent parameter 323 Commonly used Math class recursive method. 294 comma-separated list 268 Allowed promotions for Abs method in class Math 263 comma-separated list of primitive data types.cs 270 converge on a base case 297 MethodOverload. 303 call-by-value 273 260. 298 digits reversed 323 Set of recursive calls to call-by-reference 273 divide-and-conquer approach method fibonacci. 262 computer-assisted instruction CrapsGame. 318 A scoping example.cs 298 automatic initialization of a constant variable 320 FibonacciTest. 270 blocks nested 293 craps 286 RandomInt. (dot operator) 262 closing right brace (}) 321 event 281 coercion of arguments 271 event handling 281 coersion of arguments 272 Examples A coin tossing 276. Inc.cs 277 byte promotions 272 decimal promotions 272 RollDie2. 286 block is exited 293 cosine 263 Programmer-defined Maxi- block scope 293 counter-controlled repetition 304 mum method.cs 274 RollDie.) operator 262 Simulating rolling 12 six-sided caller 261 Double class 291 dice.FromString method exhausting memory 299 Ceil method in class Math 263 271 Exp method in class Math 263 Celsius equivalent of a Fahrenheit duration 293 exponential “explosion” of calls temperature 323 304 chance 276 exponential method 263 char promotions 272 E exponentiation 263 class 260 element of chance 276 extending a class 292 © Copyright 1992–2002 by Deitel & Associates. 300 break statement 293 Button class 292 D RefOutTest. 7/24/01 .cs 300 variable 293 consume memory 304 Hierarchical boss method/ automatic variables must be continue statement 293 worker method relationship. 277 Calculating factorials with a dice game 286 Scoping. 303 floating-point value 272 307 Base Class Library or BCL 260 copy of an argument 273 Program to simulate the game block 268 Cos method in class Math 263 of craps.

floor 315 O method relationship 261 Math.Min method 263 out parameter 274 Math. infinite loop 299 270 infinite recursion 299.max method 271 operator precedence 302 hypotenuse of a right triangle 317 Math.cs 298 Fahrenheit equivalent of a Celsius int promotions 272 method attribute 267 temperature 323 Int32. 320. 325 .Show method factorial 297 factorial method 297 inner block 294 262 instance variables of a class 293 method 260 FactorialTest.NET Framework 260 Math class methods 263 GroupBox class 292 . 263. All Rights Reserved.NET Framework Library 260 math library method 326 “guess the number” game 324 Next method in class Random Math.Exp method 263 hierarchical boss method/worker Math.Tan method 263 P inheritance 292 Max method in class Math 263 parameter 264.Sin method 263 overloading 305 identifier’s scope 293 Math.Floor method 263 object promotions 272 Hierarchical boss method/worker Math.Cos method 263 null 293 “hiding” of implementation details Math.Sqrt method 262. 267 init method 300 MaximumValue.Max method 263 opening left brace ({) 321 hierarchical structure 261 Math.PI 263 outer block 294 Math.2 Index F InitializeComponent message dialog 280 method 300 MessageBox.cs 270 parameter list 268 © Copyright 1992–2002 by Deitel & Associates. lifetime of an identifier 293 FromString method 262 327 likelihood 277 FromString method in class modifier 267 local variable 264.cs 306 MethodOverload2.random 322 overloaded method 305 identifier’s duration 293 Math. 7/24/01 .Log method 263 one-armed bandit 276 method relationship. 293. 304 Math.Ceil method 263 nonrecursive method call 304 H Math.cs 300 iterative 299 method integerPower 317 fillRect method of the Graphics method modifier 267 class 322 method overloading 305 J method power 325 final 320 Java APIs 259 method scope 293 float promotions 272 Floor method in class Math 263 MethodOverload.FromString method method body 268 Fibonacci method 302 262 method call 261 Fibonacci numbers 303 interface 281 method call operator 267 Fibonacci series 300 interface ActionListener 320 method factorial 298 Fibonacci series defined invoke 262 method fillRect 322 recursively 300 iteration 304 method hypotenuse 317 FibonacciTest. 262 Math. Double 271 modularizing a program with 296 methods 264 local variables of a method 294 module 260 G Log method in class Math 263 modules in C# 260 logarithm 263 gambling casino 276 monolithic program 305 long promotions 272 game playing 276 game-playing program 276 getSource() method 323 M N golden mean 300 named constant 320 make your point 286 golden ratio 300 natural logarithm 263 mangled or decorated names 305 greatest common divisor (GCD) nested block 293 Math class methods 261 319. Inc.Pow method 263 overhead of recursion 304 I Math.E 263 261 Math. 268.Abs method 263 276 Math.cs 307 Form class 269 L Format method in class Double Min method in class Math 263 Label class 292 262 mixed-type expression 272.

cs 277 shift 277 void return-value-type 268 ratio of successive Fibonacci Shifted random integers.WinForms namespace pass-by-value 273 269 292 perfect number 323 return-value-type 267 PictureBox class 292 RollDie. 286 S U programmer-defined maximum sbyte promotions 272 uint promotions 272 method 270 scaling 277 ulong promotions 272 Programmer-defined Maximum scaling factor 277.Index 3 pass-by-reference 273 return statement 267. 300 Sqrt method in class Math 263. 298 dice. 306 R Scoping. ref parameter 274 270 RefOutTest. 323 application. 299 simulation 276 recursive method factorial 298 Sin method in class Math 263 recursive method power 325 sine 263 recursive program 303 small method 269 recursively generating Fibonacci software reusability 264 numbers 303 spiral 300 Recursively generating Fibonacci Sqrt method 262 numbers. 303 signature 305.cs 277 player’s point 286 RollDie2. 277 tangent 263 precedence 302 round 263 terminating right brace (}) of a prime 323 round a number to a specific block 294 primitive (or built-in) data type decimal place 321 termination test 304 272. 264 primitive data types are initialized rounding a value to the nearest Towers of Hanoi 318 to null 293 integer 321 trigonometric cosine 263 principle of least privilege 294 rounding errors 272 trigonometric sine 263 probability 276 rules of operator precedence 302 trigonometric tangent 263 Program to simulate the game of craps. 291 © Copyright 1992–2002 by Deitel & Associates. 293 rounding 321 ToInt32 method 262. 302. Inc.cs 294 radians 263 selection structure for recursion V radius of a circle 326 304 value to the nearest integer 321 Random 291 Set of recursive calls to method video game 276 Random class 276. 303 Visualizing Recursion 325 RandomInt. 302 Box 262 recursion vs. iteration 304 side effect 303 recursive call 297. 7/24/01 .cs 281 T Pow method in class Math 263 Rolling dice in a windows Tan method in class Math 263 power 263. 277 numbers 300 shifting value 286 read-only variable 320 short promotions 272 recursion overhead 304 Show method in class Message- recursion step 297. 270 scope 293 final variables 320 programmer-defined method 261 scope (block) 293 user interface event 300 promotion rules 271 scope (class) 293 ushort promotions 272 scope of an identifier 293 Using overloaded methods. System. 286 uppercase letters in the names of method. All Rights Reserved.cs 274 square root 263 "reinventing the wheel" 261 stack 318 repetition structure for iteration statement 267 304 static duration 293 return 261 string promotions 272 return keyword 297 System namespace 262. 281 recursive method 296. 268. 291 fibonacci. 307 Recursive evaluation 298 simulate coin tossing 318 recursive evaluation 298 Simulating rolling 12 six-sided Recursive evaluation of 5!.