You are on page 1of 37

1

Topic 6 - Methods

Outline
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
6.9
6.10
6.11
6.12
6.13
6.14
6.15
6.16
6.17

Introduction
Program Modules in C#
Math Class Methods
Methods
Method Definitions
Argument Promotion
C# Namespaces
Value Types and Reference Types
Passing Arguments: Call-by-Value vs. Call-by-Reference
Random-Number Generation
Example: Game of Chance
Duration of Identifiers
Scope Rules
Recursion
Example Using Recursion: The Fibonacci Series
Recursion vs. Iteration
Method Overloading

2002 Prentice Hall. All rights reserved.

6.2 Program Modules in C#


Modules
Class
Method
Enables use of classes or methods without knowledge of
how they work, just what they should do

The .NET Framework Class Library (FCL)

Helps to increase reusability


Console
MessageBox

2002 Prentice Hall. All rights reserved.

6.2 Program Modules in C#


boss

worker1

worker4

Fig. 6.1

worker2

worker3

worker5

Hierarchical boss method/worker method relationship.

2002 Prentice Hall. All rights reserved.

6.3 Math Class Methods


The Math class
Allows the user to perform common math calculations
Using methods
ClassName.MethodName( argument1, arument2, )
List of methods are in Fig. 6.2

Constants

Math.PI = 3.1415926535
Math.E = 2.7182818285

2002 Prentice Hall. All rights reserved.

6.3 Math Class Methods


Method

Description

Example

Ceiling( x )

rounds x to the smallest integer


not less than x

Ceiling( 9.2 ) is 10.0


Ceiling( -9.8 ) is -9.0

Cos( x )

trigonometric cosine of x
(x in radians)

Cos( 0.0 ) is 1.0

Exp( x )

exponential method ex

Exp( 1.0 ) is approximately


2.7182818284590451
Exp( 2.0 ) is approximately
7.3890560989306504

Floor( x )

rounds x to the largest integer not Floor( 9.2 ) is 9.0


greater than x
Floor( -9.8 ) is -10.0

Log( x )

natural logarithm of x (base e)

Log( 2.7182818284590451 )
is approximately 1.0
Log( 7.3890560989306504 )
is approximately 2.0

Max( x, y )

larger value of x and y


(also has versions for float,
int and long values)

Max( 2.3, 12.7 ) is 12.7


Max( -2.3, -12.7 ) is -2.3

Min( x, y )

smaller value of x and y


(also has versions for float,
int and long values)

Min( 2.3, 12.7 ) is 2.3


Min( -2.3, -12.7 ) is -12.7

Pow( x, y )

x raised to power y (xy)

Pow( 2.0, 7.0 ) is 128.0


Pow( 9.0, .5 ) is 3.0

Sin( x )

trigonometric sine of x
(x in radians)

Sin( 0.0 ) is 0.0

Sqrt( x )

square root of x

Sqrt( 900.0 ) is 30.0


Sqrt( 9.0 ) is 3.0

Tan( x )

trigonometric tangent of x
(x in radians)

Tan( 0.0 ) is 0.0

absolute value of x

Abs( x )

Fig. 6.2

Commonly used

2002 Prentice Hall. All rights reserved.

Abs( 23.7 ) is 23.7


Abs( 0 ) is 0
Abs( -23.7 ) is 23.7

Math class methods.

6.4 Methods
Variables
Declared in a method = local variables
Declared outside a method = global variables
Only the method that defines them know they exist
Send parameters to communicate with other methods

Reasons for using


Divide and conquer
Reusability
Use classes and methods as building blocks for new ones

Cut down on repetition

Methods can be called from anywhere in a program

2002 Prentice Hall. All rights reserved.

6.5 Method Definitions


Writing a custom method
Header
ReturnType Properties Name( Param1, Param2, )

Body
Contains the code of what the method does
Contains the return value if necessary

For uses call elsewhere in program


Pass parameters if needed

All methods must be defined inside of a class

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Outline

// Fig. 6.3: SquareInt.cs


// A programmer-defined Square method.
using
using
using
using
using
using

System;
// includes basic data types
System.Drawing;
// for graphics capabilities
System.Collections; Start
// for
complex
data structures
of class
SquareInteger.
It implements
System.ComponentModel; // controls component behavior
System.Windows.Forms; System.Windows.Forms.Form
// for GUI development
System.Data;
// for reading outside data

Subtract.cs

// form used to display results of squaring 10 numbers


public class SquareIntegers : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
// label containing results
private System.Windows.Forms.Label outputLabel;
public SquareIntegers()
Start of the SquareIntegers
{
// Required for Windows Form Designer support
InitializeComponent();

method

int result; // store result of call to method Square

This is the methods variables. They


can only be used within the method.

2002 Prentice Hall.


All rights reserved.

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

// loop 10 times
for ( int counter = 1; counter <= 10; counter++ )
{
// calculate square of counter and store in result
result = Square( counter );
The main body

of the
SquareIntegers method

Outline
Subtract.cs

// append result to output string


outputLabel.Text += "The square of " + counter +
" is " + result + "\n";
}
} // end SquareIntegers

A call to the Square method. The


counter variable is passed to it for use.
The return value is stored in result

// Clean up any resources being used.


protected override void Dispose( bool disposing )
{
// Visual Studio .NET-generated code for method Dispose
}
// Required method for Designer support
private void InitializeComponent()
{
// Visual Studio .NET generated code
// for method InitializeComponent
}

2002 Prentice Hall.


All rights reserved.

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

// The main entry point for the application.


[STAThread]
static void Main()
{
Application.Run( new SquareIntegers() );
}

Outline
Subtract.cs

The Square method. Receives one


and returns an integer

// Square method definition


integer
int Square( int y )
{
return y * y; // return square of y
} // end method Square
} // end of class SquareIntegers

The method returns the passed


variable multiplied by itself

Program Output

2002 Prentice Hall.


All rights reserved.

10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

Outline

// Fig. 6.4: MaximumValue.cs


// Finding the maximum of three doubles.
using System;

MaximumValue.cs

class MaximumValue
{
// main entry point for application
static void Main( string[] args )
{
// obtain user input and convert to double
Console.Write( "Enter first floating-point value: " );
double number1 = Double.Parse( Console.ReadLine() );

The program gets three


values from the user

Console.Write( "Enter second floating-point value: " );


double number2 = Double.Parse( Console.ReadLine() );
Console.Write( "Enter third floating-point value: " );
double number3 = Double.Parse( Console.ReadLine() );
// call method Maximum to determine largest value
double max = Maximum( number1, number2, number3 );
// display maximum value
Console.WriteLine("\nmaximum is: " + max );

The three values are then passed


to the Maximum method for use

} // end method Main

2002 Prentice Hall.


All rights reserved.

11

28
29
30
31
32
33
34
35
36
37

// Maximum method uses method Math.Max to help determine


// the maximum value
static double Maximum( double x, double y, double z )
{
return Math.Max( x, Math.Max( y, z ) );

Outline
MaximumValue.cs

} // end method Maximum


} // end class MaximumValue

The Maximum method receives 3


variables and returns the largest one

The use of Math.Max uses the Max


method in class Math. The dot
operator is used to call it.

Enter first floating-point value: 37.3


Enter second floating-point value: 99.32
Enter third floating-point value: 27.1928

Program Output

maximum is: 99.32

2002 Prentice Hall.


All rights reserved.

12

13

6.6 Argument Promotion


Implicit Conversion
Object is converted to a needed type implicitly
Only done if complier knows no data will be lost

Explicit Conversion
Object is manually converted
Required if there could be a loss of data
Widening
Make an object that of a derived class and more complex

Narrowing

Make an object that of a base class and cause some data loss

2002 Prentice Hall. All rights reserved.

14

6.6 Argument Promotion


Type

Can be Converted to Type(s)

byte

decimal, double, float, int, uint, long, ulong, object, short or ushort

sbyte

decimal, double, float, int, long, object or short

char

decimal, double, float, int, uint, long, ulong, object or ushort

decimal

object

double

object

float

double or object

int

decimal, double, float, long or object

uint

decimal, double, float, long, ulong, or object

long

decimal, double, float or object

ulong

decimal, double, float or object

object

None

short

decimal, double, float, int, long or object

ushort

decimal, double, float, int, uint, long, ulong or object

string

object

bool

Fig. 6.5

object

Allowed implicit conversions.

2002 Prentice Hall. All rights reserved.

15

6.7 C# Namespaces
Namespace

A group of classes and their methods


FCL is composed of namespaces
Namespaces are stored in .dll files called assemblies
A list of the FLC namespaces are in Fig. 6.6
.NET Framework, class library for info on all namespaces

Included in a program with the using keyword

2002 Prentice Hall. All rights reserved.

16

6.7 C# Namespaces
Namespace

Description

System.Data

Contains classes that form ADO .NET, used for database


access and manipulation.

System.Drawing

Contains classes used for drawing and graphics.

System.IO

Contains classes for the input and output of data, such as with
files.

System.Threading

Contains classes for multithreading, used to run multiple parts


of a program simultaneously.

System.Windows.Forms

Contains classes used to create graphical user interfaces.

System.Xml

Contains classes used to process XML data.

System

Fig. 6.6

Contains essential classes and data types (such as int,


double, char, etc.). Implicitly referenced by all C#
programs.

Namespaces in the Framework Class Library.

2002 Prentice Hall. All rights reserved.

17

6.8 Value Types and Reference Types


Value types
Contains data of the specified type
Programmer created
structs
enumerations (Chapter 8)

Reference types
Contain an address to a spot in memory where the data is
Programmer create
Classes (Chapter 8)
Interfaces (Chapter 8)
Delegates (Chapter 9)

All values are 32bit allowing cross-platform use


2002 Prentice Hall. All rights reserved.

6.9 Passing Arguments: Call-By-Value vs.


Call-By-Reference
Passing by value
Send a method a copy of the object
When returned are always returned by value
Set by value by default

Passing by reference
Send a method the actual reference point
Causes the variable to be changed throughout the program

When returned are always returned by reference


The ref keyword specifies by reference
The out keyword means a called method will initialize it

2002 Prentice Hall. All rights reserved.

18

19

6.10 Random Number Generation


Class Random
Within namespace System
Truly random
The numbers are generated using an equations with a seed
The seed is usually the exact time of day

randomObject.Next()
Returns a number from 0 to Int32.MaxValue
Int32.MaxValue = 2,147,483,647

randomObject.Next( x )
Returns a value from 0 up to but not including x

randomObject.Next( x, y )

Returns a number between x and up to but not including y

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Outline

// Fig. 6.9: RandomInt.cs


// Random integers.
using System;
using System.Windows.Forms;

RandomInt.cs

// calculates and displays 20 random integers


class RandomInt
{
// main entry point for application
a new
object
static void Main( Creates
string[]
argsRandom
)
{
int value;
string output = "";
Random randomInteger = new Random();

Will set value to a random number


from1 up to but not including 7

// loop 20 times
for ( int i = 1; i <= 20; i++ )
{
// pick random integer between 1 and 6
value = randomInteger.Next( 1, 7 );
output += value + " "; // append value to output
// if counter divisible by 5, append newline
if ( i % 5 == 0 )
output += "\n";
} // end for structure

Format the output to only have


5 numbers per line

2002 Prentice Hall.


All rights reserved.

20

31
32
33
34
35
36

Outline

MessageBox.Show( output, "20 Random Numbers from 1 to 6",


MessageBoxButtons.OK, MessageBoxIcon.Information );
} // end Main

RandomInt.cs

} // end class RandomInt

Display the output in a message box

Program Output

2002 Prentice Hall.


All rights reserved.

21

22

6.12 Duration of Identifiers


Duration
The amount of time an identifier exist in memory

Scope
The section of a program in which the object can be
referenced

Local variables
Created when declared
Destroyed when the block exits
Not initialized

Most variables are set to 0


All bool variables are set to false
All reference variables are set to null
2002 Prentice Hall. All rights reserved.

23

6.13 Scope Rules


Scope
Portion of a program in which a variable can be accessed
Class scope
From when created in class
Until end of class (})
Global to all methods in that class
Direct modification
Repeated names causes previous to be hidden until scope ends

Block scope

From when created


Until end of block (})
Only used within that block
Must be passed and modified indirectly
Cannot repeat variable names
2002 Prentice Hall. All rights reserved.

24

6.14 Recursion
Recursive methods
Methods that call themselves
Directly
Indirectly
Call others methods which call it

Continually breaks problem down to simpler forms


Must converge in order to end recursion
Each method call remains open (unfinished)

Finishes each call and then finishes itself

2002 Prentice Hall. All rights reserved.

25

6.14 Recursion
Final value = 120
5!

5!
5! = 5 * 24 = 120 is returned
5 * 4!
4! = 4 * 6 = 24 is returned
4 * 3!
3! = 3 * 2 = 6 is returned
3 * 2!

5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
(a) Procession of recursive calls.

Fig. 6.14 Recursive evaluation of 5!.

2002 Prentice Hall. All rights reserved.

2! = 2 * 1 = 2 is returned
2 * 1!
1

1 returned

(b) Values returned from each recursive call.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Outline

// Fig. 6.15: FactorialTest.cs


// Recursive Factorial method.
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

FactorialTest.cs

public class FactorialTest : System.Windows.Forms.Form


{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label outputLabel;
public FactorialTest()
{
InitializeComponent();
for ( long i = 0; i <= 10; i++ )
outputLabel.Text += i + "! = " +
Factorial( i ) + "\n";
}

2002 Prentice Hall.


All rights reserved.

26

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

Outline

// Visual Studio .NET-generated code


public long Factorial( long number )
{
if ( number <= 1 )
// base case
return 1;

The Factorial method


calls itself (recursion)

FactorialTest.cs

else
return number * Factorial( number - 1 );
}

The recursion ends when


[STAThread]
static void Main()
the value is less than or
{
equal to 1
Application.Run( new FactorialTest());
}
} // end of class FactorialTest

Program Output

2002 Prentice Hall.


All rights reserved.

27

6.15 Example Using Recursion: The


Fibonacci Sequence
Fibonacci Sequence

F(0) = 0
F(1) = 1
F(n) = F(n - 1) + F(n - 2)
Recursion is used to evaluate F(n)

Complexity theory

How hard computers need to work to perform algorithms

2002 Prentice Hall. All rights reserved.

28

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Outline

// Fig. 6.16: FibonacciTest.cs


// Recursive fibonacci method.
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

FibonacciTest.cs

public class FibonacciTest : System.Windows.Forms.Form


{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button calculateButton;
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.Label displayLabel;
private System.Windows.Forms.Label promptLabel;
public FibonacciTest()
{
InitializeComponent();
}
// Visual Studio .NET-generated code

2002 Prentice Hall.


All rights reserved.

29

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

// call Fibonacci and display results


protected void calculateButton_Click(
object sender, System.EventArgs e )
{
string numberString = ( inputTextBox.Text );
int number = System.Convert.ToInt32( numberString );
int fibonacciNumber = Fibonacci( number );
displayLabel.Text = "Fibonacci Value is " + fibonacciNumber;
}

Outline
FibonacciTest.cs

// calculates Fibonacci number


public int Fibonacci( int number )
{
if ( number == 0 || number == 1 )
The number uses the Fibonacci
return number;
method to get its result
else
return Fibonacci( number - 1 ) + Fibonacci( number - 2 );
}
[STAThread]
Calls itself twice, to get the result
The recursion ends when
static void Main()
of the the two previous numbers
the number is 0 or 1
{
Application.Run( new FibonacciTest() );
}
} // end of class FibonacciTest

2002 Prentice Hall.


All rights reserved.

30

Outline
FibonacciTest.cs
Program Output

2002 Prentice Hall.


All rights reserved.

31

6.15 Example Using Recursion: The


Fibonacci Sequence

F( 3 )

return F( 2 )

return F( 1 )

return 1

F( 0 )

F( 1 )

return 1

return 0

Fig. 6.17 Set of recursive calls to method Fibonacci (abbreviated as F).

2002 Prentice Hall. All rights reserved.

32

33

6.16 Recursion vs. Iteration


Iteration
Uses repetition structures
while, do/while, for, foreach

Continues until counter fails repetition case

Recursion
Uses selection structures
if, if/else, switch

Repetition through method calls


Continues until a base case is reached
Creates a duplicate of the variables

Can consume memory and processor speed

2002 Prentice Hall. All rights reserved.

34

6.17 Method Overloading


Methods with the same name
Can have the same name but need different arguments
Variables passed must be different
Either in type received or order sent

Usually perform the same task

On different data types

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Outline

// Fig. 6.18: MethodOverload.cs


// Using overloaded methods.
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

MethodOverload.cs

public class MethodOverload : System.Windows.Forms.Form


{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label outputLabel;
public MethodOverload()
{
InitializeComponent();
// call both versions of Square
outputLabel.Text =
"The square of integer 7 is " + Square( 7 ) +
"\nThe square of double 7.5 is " + Square ( 7.5 );
}

Two versions of the square


method are called

// Visual Studio .NET-generated code

2002 Prentice Hall.


All rights reserved.

35

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

// first version, takes one integer


public int Square ( int x )
One method takes an
{
return x * x;
int as parameters
}

Outline
MethodOverload.cs

// second version, takes one double


public double Square ( double y )
{
return y * y;
}
The

other version of the method uses


a double instead of an integer

[STAThread]
static void Main()
{
Application.Run( new MethodOverload() );
}
} // end of class MethodOverload

Program Output

2002 Prentice Hall.


All rights reserved.

36

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Outline

// Fig. 6.19: MethodOverload2.cs


// Overloaded methods with identical signatures and
// different return types.

MethodOverload2.cs

using System;
class MethodOverload2
{
public int Square( double x )
This
{
return x * x;
}

37

method returns an integer

// second Square method takes same number,


// order and type of arguments, error
public double Square( double y )
{
return y * y;
This method returns
}
// main entry point for application
static void Main()
{
int squareValue = 2;
Square( squareValue );
}

a double number

Since the compiler cannot tell


which method to use based on
passed values an error is generated

} // end of class MethodOverload2

Program Output

2002 Prentice Hall.


All rights reserved.

You might also like