M M E E in C# in C# I I K K 204111 Computer & - - PowerPoint PPT Presentation

m m e e
SMART_READER_LITE
LIVE PREVIEW

M M E E in C# in C# I I K K 204111 Computer & - - PowerPoint PPT Presentation

Writing Writing Methods Methods M M E E in C# in C# I I K K 204111 Computer & Programming Dr.Arnon Rungsawang http://mike.cpe.ku.ac.th/204111 2 K K 204111 Computer & Programming - Writing Methods I I E M M E


slide-1
SLIDE 1

M M E E K K

I I

Writing Writing Methods Methods

in C# in C#

204111 Computer & Programming

Dr.Arnon Rungsawang

http://mike.cpe.ku.ac.th/204111

slide-2
SLIDE 2

204111 Computer & Programming - Writing Methods

2

Version 2008/1

M M E E

K K I I

slide-3
SLIDE 3

204111 Computer & Programming - Writing Methods

3

Version 2008/1

M M E E

K K I I

Classes & Methods Classes & Methods

static void myHello() { // method body Console.WriteLine(“Hello World!”) } class HelloWorld { public static void Main () { myHello(); } … }

slide-4
SLIDE 4

204111 Computer & Programming - Writing Methods

4

Version 2008/1

M M E E

K K I I

Standard Classes Standard Classes

  • C# Framework Class Library (FCL) defines many

classes, e.g.,

– Console – MessageBox – Int32 – Math

  • The definition of a class includes both methods and data

properties:

– methods, e.g.,

  • Console.WriteLine( )
  • Int32.Parse( )
  • Math.Cos( )
  • MessageBox.Show( )

– data properties, e.g.,

  • Int32.MinValue
  • Int32.MaxValue
  • Math.PI
  • Math.E
slide-5
SLIDE 5

204111 Computer & Programming - Writing Methods

5

Version 2008/1

M M E E

K K I I

Methods Methods

  • A method

method’ ’s name s name should provide a well-defined, easy-to- understand functionality.

– A method takes input (parameters) takes input (parameters), performs some actions performs some actions, and (sometime) returns a value returns a value.

  • Example: invoking the WriteLine method of the

Console class:

Console.WriteLine ( “The ultimate conflict begins...”); class method Information provided to the method (parameters or called “arguments”) dot

slide-6
SLIDE 6

204111 Computer & Programming - Writing Methods

6

Version 2008/1

M M E E

K K I I

Example: Example: Math Math class methods class methods

Me tho d De sc r iptio n E xample Abs( x ) absolute value of x Abs( 23.7 ) is 23.7 Abs( 0 ) is 0 Abs( -23.7 ) is 23.7 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 greater than x Floor( 9.2 ) is 9.0 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 Co mmo nly use d Math c lass me tho ds.

slide-7
SLIDE 7

204111 Computer & Programming - Writing Methods

7

Version 2008/1

M M E E

K K I I

Methods provide abstraction Methods provide abstraction

  • An abstraction

abstraction hides (or ignores) the right details at the right time.

– A method is abstract in that we don't really have to think about its internal details in order to use it.

  • e.g., we don't need to know how the WriteLine method

works in order to invoke it.

  • Why abstraction?

– Easier to reuse – Easier to understand – – Divide and conquer Divide and conquer

slide-8
SLIDE 8

204111 Computer & Programming - Writing Methods

8

Version 2008/1

M M E E

K K I I

Method Method’ ’s header s header

  • A method declaration begins with a method header.

method method name name return return type type parameter list parameter list The parameter list specifies the type The parameter list specifies the type and name of and name of each each parameter. parameter. The name of a parameter in the method The name of a parameter in the method declaration is called a declaration is called a formal argument, formal argument,

  • r a
  • r a formal parameter.

formal parameter. class MyClass {

static int SquareSum( int num1, int num2 )

… properties properties

method header

slide-9
SLIDE 9

204111 Computer & Programming - Writing Methods

9

Version 2008/1

M M E E

K K I I

Method Method’ ’s body s body

  • The method header is followed by the method body.

static int SquareSum(int num1, int num2) { // method body int sum = num1 + num2; return sum * sum; } class MyClass { … … }

method body

slide-10
SLIDE 10

204111 Computer & Programming - Writing Methods

10

Version 2008/1

M M E E

K K I I

return return Statement Statement

  • The return

return type of a method indicates the type type of value that the method sends back sends back to the calling calling location location.

  • A method that does not return a value has a

void return type.

  • The return

return statement statement specifies the value that will be returned.

– Its expression must conform to the return type.

static int SquareSum(int num1, int num2) { // method body int sum = num1 + num2; return (sum * sum); } class MyClass { … … } return int

slide-11
SLIDE 11

204111 Computer & Programming - Writing Methods

11

Version 2008/1

M M E E

K K I I

Calling a method Calling a method

  • Each time a method is called, the actual arguments

actual arguments in the invocation are copied copied into the formal arguments formal arguments.

static int SquareSum (int num1, int num2) { int sum = num1 + num2; return sum * sum; } int num = SquareSum (2, 3); See SquareSum.cs

Caller in Caller in Main( ) Main( )

slide-12
SLIDE 12

204111 Computer & Programming - Writing Methods

12

Version 2008/1

M M E E

K K I I

Methods in standard classes Methods in standard classes

  • The Console

Console class

– The Write and WriteLine methods

  • The S

String tring class

– The Format method: e.g.,

String.Format( “{0:C}”, 2.0 )

See TestMethods.cs

slide-13
SLIDE 13

204111 Computer & Programming - Writing Methods

13

Version 2008/1

M M E E

K K I I

Methods in standard classes (2) Methods in standard classes (2)

  • The MessageBox

MessageBox class

– The Show Show method we will use has four parameters

  • text to be displayed, caption, buttons, icon.

Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog

  • button. (Optional)

Argument 2: Title bar string (Optional) Argument 1: Message to display

slide-14
SLIDE 14

204111 Computer & Programming - Writing Methods

14

Version 2008/1

M M E E

K K I I

1 // Sum.cs 2 // Summation with the for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Sum 8 { 9 static void Main( string[] args ) 10 { 11 int sum = 0; 12 13 for ( int number = 2; number <= 100; number += 2 ) 14 sum += number; 15 16 MessageBox.Show( "The sum is " + sum, 17 "Sum Even Integers from 2 to 100", 18 MessageBoxButtons.OK, 19 MessageBoxIcon.Information ); 20 21 } // end method Main 22 23 } // end class Sum

Argument 4: MessageBox Icon (Optional) Argument 3: OK dialog

  • button. (Optional)

Argument 2: Title bar string (Optional) Argument 1: Message to display

slide-15
SLIDE 15

204111 Computer & Programming - Writing Methods

15

Version 2008/1

M M E E

K K I I

MessageBox MessageBox Buttons Buttons

Me ssageBo x B uttons Desc riptio n MessageBoxButton.OK

Specifies that the dialog should include an OK button.

MessageBoxButton.OKCancel

Specifies that the dialog should include OK and Cancel buttons. Warns the user about some condition and allows the user to either continue

  • r cancel an operation.

MessageBoxButton.YesNo

Specifies that the dialog should contain Yes and No buttons. Used to ask the user a question.

MessageBoxButton.YesNoCancel

Specifies that the dialog should contain Yes, No and Cancel buttons. Typically used to ask the user a question but still allows the user to cancel the operation.

MessageBoxButton.RetryCancel

Specifies that the dialog should contain Retry and Cancel buttons. Typically used to inform a user about a failed operation and allow the user to retry or cancel the operation.

MessageBoxButton.AbortRetryIgnore Specifies that the dialog should contain Abort,

Retry and Ignore buttons. Typically used to inform the user that one of a series of operations has failed and allow the user to abort the series of

  • perations, retry the failed operation or ignore

the failed operation and continue.

Buttons fo r message dialo gs.

slide-16
SLIDE 16

204111 Computer & Programming - Writing Methods

16

Version 2008/1

M M E E

K K I I

MessageBox MessageBox Icons Icons

Me ssage Bo x I c o ns I c o n De sc riptio n MessageBoxIcon.Exclamation Displays a dialog with an exclamation point. Typically used to caution the user against potential problems. MessageBoxIcon.Information Displays a dialog with an informational message to the user. MessageBoxIcon.Question Displays a dialog with a question

  • mark. Typically used to ask the

user a question. MessageBoxIcon.Error Displays a dialog with an x in a red circle. Helps alert user of errors or important messages. I c o ns fo r me ssage dialo gs.

slide-17
SLIDE 17

204111 Computer & Programming - Writing Methods

17

Version 2008/1

M M E E

K K I I

1 // Interest.cs 2 // Calculating compound interest, using MessageBox and Pow. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Interest 8 { 9 static void Main( string[] args ) 10 { 11 decimal amount, principal = ( decimal ) 1000.00; 12 double rate = .05; 13 string output; 14 15

  • utput = "Year\tAmount on deposit\n";

16 17 for ( int year = 1; year <= 10; year++ ) 18 { 19 amount = principal * 20 ( decimal ) Math.Pow( 1.0 + rate, year ); 21 22

  • utput += year + "\t" +

23 String.Format( "{0:C}", amount ) + "\n"; 24 } 25 26 MessageBox.Show( output, 27 "Compound Interest", 27 MessageBoxButtons.OK, 28 MessageBoxIcon.Information ); 29 } // end method Main 30 } // end class Interest

slide-18
SLIDE 18

204111 Computer & Programming - Writing Methods

18

Version 2008/1

M M E E

K K I I

A brief introduction to make you feel comfortable about using such methods. We will explore the full glory later.

slide-19
SLIDE 19

204111 Computer & Programming - Writing Methods

19

Version 2008/1

M M E E

K K I I

Class Methods (i.e., Static Methods) Class Methods (i.e., Static Methods)

  • We use class

class mainly to define related methods related methods together:

– Eg., all math related methods are defined in the Math Math class.

  • The methods we have seen are defined as

static static (or class class) methods methods.

– To make a method static, a programmer applies the static modifier modifier to the method definition. – The result of each invocation of a class (static) method is completely determined by the actual parameters actual parameters.

slide-20
SLIDE 20

204111 Computer & Programming - Writing Methods

20

Version 2008/1

M M E E

K K I I

Motivation for Objects Motivation for Objects

  • But sometime we want a method to keep

keep (internal) state (internal) state after each call.

  • For example, random number generator

– A computer may generate a sequence of random numbers using the following formula: Xn = 75 Xn-1 mod (231 – 1) – To write a method called GetNextRandom() we have to give the method the previous number: int GetNextRandom( ) { return 75 * previous % ( 231 – 1 ); } – Method created without without a static modifier is called an “instance method instance method”.

slide-21
SLIDE 21

204111 Computer & Programming - Writing Methods

21

Version 2008/1

M M E E

K K I I

GetNextRandom GetNextRandom( ) ( )

using System; class myRandom { int previous; myRandom() { this.previous=1;} //constructor myRandom(int s) { this.previous=s;} //constructor int GetNextRandom() // instance method instance method { int now = (int)(Math.Pow(7,5) * this.previous % (Math.Pow(2,31)-1)); this.previous=now; return now; } public static void Main() { myRandom a = new new myRandom(5); // instance creation myRandom b = new new myRandom(50); while (true) { Console.WriteLine("{0} {1}", a.GetNextRandom(), b.GetNextRandom()); Console.ReadLine(); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

slide-22
SLIDE 22

204111 Computer & Programming - Writing Methods

22

Version 2008/1

M M E E

K K I I

GetNextRandom GetNextRandom( ) ( )

Object a previous= 5 myRandom a = new myRandom(5); Object b previous= 50 myRandom b = new myRandom(50); a.GetNextRandom(); Object a previous= 84035 a.GetNextRandom(); Object a previous= 1412376245 b.GetNextRandom(); Object b previous= 840350 b.GetNextRandom(); Object b previous= 1238860568

slide-23
SLIDE 23

204111 Computer & Programming - Writing Methods

23

Version 2008/1

M M E E

K K I I

Objects Objects

  • Class: a concept, e.g.,

– the dog concept, the house concept, …

  • Object

– An instance of a concept, e.g., the dog at my home. – An object has internal state

  • This is called encapsulation

encapsulation.

– Thus the action (method) may depend on depend on both parameters parameters and internal state internal state. myRandom(int s) { this.previous=s;} //constructor int GetNextRandom() // instance method instance method { int now = (int)(Math.Pow(7,5) * this.previous % (Math.Pow(2,31)-1)); this.previous=now; return now; }

slide-24
SLIDE 24

204111 Computer & Programming - Writing Methods

24

Version 2008/1

M M E E

K K I I

Creating and Accessing Objects Creating and Accessing Objects

  • We use the new operator to create an object

Random myRandom; myRandom = new Random();

This calls the This calls the Random Random constructor constructor, which is , which is a special method that sets up the object a special method that sets up the object

  • Creating an object is called instantiation

instantiation

– An object is an instance instance of a particular class.

  • To call a method on an object, we use the

variable (not the class), e.g.,

Random generator1 = new Random(); int num = generate1.Next();

slide-25
SLIDE 25

204111 Computer & Programming - Writing Methods

25

Version 2008/1

M M E E

K K I I

Example: the Example: the Random Random class class

Random Random ()

Random methods

int Next ()

// returns an integer from 0 to Int32.MaxValue

int Next (int max)

// returns an integer from 0 upto but not including max

int Next (int min, int max)

// returns an integer from min upto but not including max

double NextDouble ( )

// returns a double number from 0 to 1

See RandomNumbers.cs

slide-26
SLIDE 26

204111 Computer & Programming - Writing Methods

26

Version 2008/1

M M E E

K K I I

slide-27
SLIDE 27

204111 Computer & Programming - Writing Methods

27

Version 2008/1

M M E E

K K I I

Why we need to write methods? Why we need to write methods?

  • Long main program is

– hard to read and understand, – hard to debug, – hard to improve or update.

  • Normally, a (big) program

– should be divided into several sub-programs, each has its own clear duty. – has some parts that must be performed repeatedly.

class Atm { } void Main() { … ; … ; }

slide-28
SLIDE 28

204111 Computer & Programming - Writing Methods

28

Version 2008/1

M M E E

K K I I

Start ATM Check pin code Service menu withdraw balance? deposit more service Stop

slide-29
SLIDE 29

204111 Computer & Programming - Writing Methods

29

Version 2008/1

M M E E

K K I I

Write a program with methods Write a program with methods

  • How to write a big

program?

– Divide program into several parts. – Write each part with a new method. – Each method has its own clear duty to perform. – Call each method in Main(), or we can call a method inside a method?

class Atm { } void Main() { withdraw(); deposit(); balance(); } withdraw() { } deposit() { } balance() { } etc() { }

slide-30
SLIDE 30

204111 Computer & Programming - Writing Methods

30

Version 2008/1

M M E E

K K I I

When we write a new program When we write a new program

  • Think and try to reuse the old codes written

before (the same way as we reuse Console.WriteLine()).

  • Extend from the old codes.
  • Think to use methods provided by the standard

C# library.

– Console, Math, MessageBox, …

  • If we need to write a new one, think about

– Readability – Maintainability – Reusability

slide-31
SLIDE 31

204111 Computer & Programming - Writing Methods

31

Version 2008/1

M M E E

K K I I

Methods we Methods we’ ’ve already seen ve already seen

Console.WriteLine(“Hello World!”); Send string “Hello World” to standard output. int x = int.Parse(Console.ReadLine()); Get string from standard input and send to int.Parse() to convert that string into integer and keep result in variable x. Console.WriteLine(“{ 0} ! = { 1} ”, n, fac(n)); Call method fac() with argument n and send the result to standard output. if IsPrime(x) res + = x; Call method IsPrime with x.

slide-32
SLIDE 32

204111 Computer & Programming - Writing Methods

32

Version 2008/1

M M E E

K K I I

Methods in Math class Methods in Math class

  • All can be used in namespace “System”.
  • Call with “Math.”, eg., “Math.PI”

– Abs(x) : absolute value – Pow(x,y) : xy – Sqrt(x) : square root – Log(x) : natural log (base e) – Exp(x) : ex – Sin(x) : trigonometric sine – Cos(x) : trigonometric cosine – Tan(x) : trigonometric tangent – PI : π – E : e – …

Click to see Math member at msdn.

slide-33
SLIDE 33

204111 Computer & Programming - Writing Methods

33

Version 2008/1

M M E E

K K I I

Example of Example of Math.Cos Math.Cos

.NET Framework Class Library Math.Cos Method

Return the cosine of the specified angle. C# Public static double Cos (double d); Param eters d An angle, measured in radian. Return Value The cosine of d. Rem arks The angle, d, must be in radians. Multiply by n/ 180 to convert degrees to radians. Exam ple …

Click to see Math.Cos at msdn.

slide-34
SLIDE 34

204111 Computer & Programming - Writing Methods

34

Version 2008/1

M M E E

K K I I

Find angle between 2 vectors Find angle between 2 vectors

  • Requirement

– Find angle (in degrees) between the two vectors.

  • Analysis

– Both vector begin from the origin (0,0). – Get both vectors from stdin: (ux,uy) and (vx,vy). – Calculate the angle between them from – Output the result to stdout.

( )( )⎟

⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + + =

− 2 2 2 2 1

cos

y x y x y y x x

v v u u v u v u θ

(ux,uy) (vx,vy) θ (0,0)

slide-35
SLIDE 35

204111 Computer & Programming - Writing Methods

35

Version 2008/1

M M E E

K K I I

Write repeated codes into methods Write repeated codes into methods

( )( )⎟

⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + + =

2 2 2 2

) cos(

y x y x y y x x

v v u u v u v u θ

… double cosine= (Ux* Vx+ Uy* Vy)/ ((length(Ux,Uy)* length(Vx,Vy)); double degree= Math.Acos(cosine)* 180/ Math.PI; … public static double length(double x, double y) { return Math.Sqrt(x* x+ y* y); }

slide-36
SLIDE 36

204111 Computer & Programming - Writing Methods

36

Version 2008/1

M M E E

K K I I

Calculate angles between 2 vectors Calculate angles between 2 vectors

using System; class AngleBetweenTwoVectors { public static void Main() { double Ux, Uy, Vx, Vy; Ux= ReadInput("Ux"); Uy= ReadInput("Uy"); Vx= ReadInput("Vx"); Vy= ReadInput("Vy"); double cosine = (Ux* Vx + Uy* Vy)/ (length(Ux,Uy) * length(Vx,Vy)); double degree = Math.Acos(cosine) * 180 / Math.PI; Console.WriteLine("Angle between the two vectors is [ { 0} ] .", degree); Console.ReadLine(); } static double ReadInput(string s) / / method ReadInput() { Console.Write("Please enter { 0} : ", s); return Double.Parse(Console.ReadLine()); } static double length(double x, double y) / / method length() { return Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2); } }

click

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

slide-37
SLIDE 37

204111 Computer & Programming - Writing Methods

37

Version 2008/1

M M E E

K K I I

Method structure Method structure

  • Method header

– tell us how to use the method. – consists of the method property, data type of the result when finished, method name, and parameters it needs.

  • Method body

– Declaration of local variables. – Method statements (can call another method inside a method). – Return something to the caller.

static double length(double x, double y) / / method length() { return Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2); } 1 2 3 4

slide-38
SLIDE 38

204111 Computer & Programming - Writing Methods

38

Version 2008/1

M M E E

K K I I

Method structure (2) Method structure (2)

static double length(double x, double y) / / method length() { return Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2); }

method property return data type method name parameters method body Return to the caller with the same type of data as declared in the method header method header

slide-39
SLIDE 39

204111 Computer & Programming - Writing Methods

39

Version 2008/1

M M E E

K K I I

Method header : return data types Method header : return data types

  • Simple data types, eg., int, double, bool, char,…
  • Class, eg., string, point (discuss later)
  • Return nothing, ie., void

static int max(int a, int b) int res= max(35, 47); static string toString(int i, int radix) string s= toString(10, 16); static void gc() gc();

If that method returns something, we always found it inside another method or on the right side of assignment

  • perator!

int x= int.Parse(Console.ReadLine());

slide-40
SLIDE 40

204111 Computer & Programming - Writing Methods

40

Version 2008/1

M M E E

K K I I

Method header : method name Method header : method name

  • Use a valid identifier

– Begin with letter or ‘_’ – Can be composed of letter, digit, and ‘_’ – Case sensitive – Cannot use reserve word reserve word as method name – In general, the first letter is lower case. – In general, the method name is verb.

  • Some examples:

– fillCircle, turnLeft, launchRocket, fireTopedo

slide-41
SLIDE 41

204111 Computer & Programming - Writing Methods

41

Version 2008/1

M M E E

K K I I

Method header : parameters Method header : parameters

  • Treat as local variables

local variables that can only be used in that method.

  • Each parameter is written in the same way as

variable declaration, one by one

  • ne by one, but no

no semi- colon at the end.

  • Each parameter is separated by comma

comma.

  • In some case, no parameter is needed, so we

just only write nothing within the parenthesis ().

static void turnLeft(double angle) static bool launchRocket(double speed, string destination) static string readString()

slide-42
SLIDE 42

204111 Computer & Programming - Writing Methods

42

Version 2008/1

M M E E

K K I I

Method body Method body

using System; class readInt { static void Main() { Console.WriteLine("OUTPUT: { 0} ", readInt()); Console.ReadLine(); } static int readInt() { int x= 0; / / local variable bool success= false; / / local variable do { try { Console.Write(“Type something”); x= int.Parse(Console.ReadLine()); success= true; } catch (Exception e) { Console.WriteLine(e.Message); success= false; } } while (!success); return x; / / return to the caller at line 4 } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

click

slide-43
SLIDE 43

204111 Computer & Programming - Writing Methods

43

Version 2008/1

M M E E

K K I I

Method body : Method body : return return

  • return

return command will bring back the execution to the caller.

  • Data may (not) be sent back to the caller.

– The only one data that can be returned must have the same data type as declared in the header. – When nothing returns, we can just write “return();” – The last statement in the method body can act as an implicit return implicit return, when we have nothing to return to the caller.

static void printSomething(string name) { Console.Write(“Hello, ”); Console.WriteLine(“{ 0} !”, name); } static long clip(long a) { if (a> 0) return a; else return 0; / / 0 is promoted to 0L }

slide-44
SLIDE 44

204111 Computer & Programming - Writing Methods

44

Version 2008/1

M M E E

K K I I

Method body : Method body : local variables local variables

  • A local variable has scope, or can be used

– within the method body, – within the block it has been declared, or block that is found inside the outer block, – after it has been declared.

static void test(int a) { int z= 7; { int x= z; Console.WriteLine(x); } Console.WriteLine(x); / / wrong { Console.WriteLine(x); / / wrong int x= z; Console.WriteLine(x); { int y= z; Console.WriteLine(y); } { int x= z; Console.WriteLine(x); } / / wrong } } 1 2 3 4 5 6 7 8 9 10 11

slide-45
SLIDE 45

204111 Computer & Programming - Writing Methods

45

Version 2008/1

M M E E

K K I I

Method body : local variables (2) Method body : local variables (2)

  • A local variables

– is created at the point where it is declared, but without any implicit intialization. – is destroyed when the block is finished.

  • Variables declared within parameter list are treated as

local variables.

class A { static void Main(string [ ] args) { int s= 0, n= int.Parse(Console.ReadLine()); for(int i= 0; i< = n; i+ + ) { int i2= i* i; s+ = i2; int i3= i2* i; s+ = i3; } Console.WriteLine(s); } } 1 2 3 4 5 6 7 8 9 10 11 12 s,n i i2 i3

slide-46
SLIDE 46

204111 Computer & Programming - Writing Methods

46

Version 2008/1

M M E E

K K I I

Errors found when using methods ? Errors found when using methods ?

public static printSomething(string msg) { Console.WriteLine(msg); } public static int myAbs(int n) { if (a< 0) a= -a; } public static float myMax(float x, y) { return (x> y)?x: y; } public static double length(double x, double y) { double x= Math.Abs(x); return Math.Sqrt(x* x + y* y); } public static float getBlackColor() { return 0.0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

slide-47
SLIDE 47

204111 Computer & Programming - Writing Methods

47

Version 2008/1

M M E E

K K I I

Calling a method Calling a method

  • Pass some data through arguments.
  • Bring back result from return value.
  • Sometime, no value passes and returns.

int a, b; … b = power ( a+ 2 , 3 ); … public static int power (int x , int y ) { int p = 1; for (int i= 1; i< = y; i+ + ) p * = x; return p ; }

slide-48
SLIDE 48

204111 Computer & Programming - Writing Methods

48

Version 2008/1

M M E E

K K I I

Calling a method : parameters Calling a method : parameters

  • The number of parameters passing through a

method must be the same number as declared in the method header.

  • The type of the parameters must be the same,

but sometime promotion can be occurred.

public static float max(float x, float y) { … } x= max( (float) (a/ 3.0), 1f ); y= max( Float.Parse(str), 1 ); / / 1 -> 1.0f x= max( (float) (a/ 2) ); / / wrong number of args y= max( “1.0”, 1 ); / / cannot promote “1.0” to 1f

  • k

not ok

slide-49
SLIDE 49

204111 Computer & Programming - Writing Methods

49

Version 2008/1

M M E E

K K I I

Calling method : return value Calling method : return value

  • In case that a method has returned something,

we have to assign that value to a proper variable.

public static float max(float x, float y) { … } double x = max( 1.0f , (int) (x/ 3) ); int y = (int) max( 1 , 2 ); float z = max( max(x,y) , 10.5f ); long x = max( 4.0f , 2.3f ); / / float to long float y= max( 4.0 , 1.0 ); / / double to float max( 2.0f , 1.0f ); / / max return float

  • k

not ok

slide-50
SLIDE 50

204111 Computer & Programming - Writing Methods

50

Version 2008/1

M M E E

K K I I

Integration using mid Integration using mid-

  • point rule

point rule

  • Divide the area under curve into many small

rectangles.

  • Sum those areas using the mid-point rule.

n a b h − =

∑ ∫

= − +

n i i i b a

x x f h dx x f

1 1

) 2 ( . ) (

x0 x1 x2 xn f(x)

slide-51
SLIDE 51

204111 Computer & Programming - Writing Methods

51

Version 2008/1

M M E E

K K I I

Integration using mid Integration using mid-

  • point rule (2)

point rule (2)

using System; class Integration { public static void Main() { Console.WriteLine(midPoint(1.0, 3.0, 1000)); Console.ReadLine(); } static double midPoint(double a, double b, int n) { double h, x, area= 0.0; h= (b-a)/ n; x= a+ h/ 2.0; for (int i= 1; i< = n; i+ + ) { area+ = h* f(x); x+ = h; } return area; } static double f(double x) { / / f(x) = 2* x^ 2 return 2* x* x; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

x0 x1x2 xn f(x)

n a b h − =

∑ ∫

= − +

n i i i b a

x x f h dx x f

1 1

) 2 ( . ) (

slide-52
SLIDE 52

204111 Computer & Programming - Writing Methods

52

Version 2008/1

M M E E

K K I I

Integration using Simpson Integration using Simpson’ ’s rule s rule

n a b h − =

  • Divide the area under curve into many small ones.
  • Sum those areas using Simpson’s rule.

x0 x1 x2 xn f(x)

⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + ⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + ⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + ≈

∑ ∑ ∫

− = − =

) ( ) ( 2 ) ( 4 ) ( 3 ) (

2 ,... 6 , 4 , 2 1 ,... 5 , 3 , 1

b f ih a f ih a f a f h dx x f

n i n i b a

slide-53
SLIDE 53

204111 Computer & Programming - Writing Methods

53

Version 2008/1

M M E E

K K I I

Integration using Simpson Integration using Simpson’ ’s rule (2) s rule (2)

static double simpson(double a, double b, int n) { double s1, s2, x, h= (b-a)/ n; s1= s2= 0.0; x= a; for (int i= 1; i< = n; i+ + ) { x+ = h; if (i% 2= = 1) / / is odd? s1+ = f(x); else s2+ = f(x); } return (h/ 3 * (f(a)+ (4* s1)+ (2* s2)+ f(b))); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 n a b h − =

x0 x1 x2 xn f(x)

⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + ⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + ⎟ ⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + ≈

∑ ∑ ∫

− = − =

) ( ) ( 2 ) ( 4 ) ( 3 ) (

2 ,... 6 , 4 , 2 1 ,... 5 , 3 , 1

b f ih a f ih a f a f h dx x f

n i n i b a

click

slide-54
SLIDE 54

204111 Computer & Programming - Writing Methods

54

Version 2008/1

M M E E

K K I I

Voltage across a capacitor Voltage across a capacitor

  • At t=0, electron charged at a capacitor is equal to zero, we

switch on the circuit.

  • At t=1, we switch off the circuit which supply the current
  • Electron charge at time t is
  • Thus, voltage across the capacitor is

) 1 ( ) 1 ( 4 ) (

) 1 ( 5 . 5 . t t

e e e t I

− − − −

− − =

= dt t I t Q ) ( ) (

C t Q t V ) ( ) ( =

V(t) C

slide-55
SLIDE 55

204111 Computer & Programming - Writing Methods

55

Version 2008/1

M M E E

K K I I

public static void Main() { double c= 0.05; / / capacitor 0.05 farad double v, q; / / voltage and charge double a= 1.0, b= 10.0; / / 1 to 10 seconds for (double t= 1; t< = b; t+ + ) { q= simpson(a, t, 1000); v= q/ c; Console.WriteLine("t= { 0} \ tq= { 1} \ tv= { 2} ", t, q, v); } } static double simpson(double a, double b, int n) { … ; } static double f(double t) { double y= 4* (1-Math.Exp(-0.5)); y* = Math.Exp(-0.5* (t-1)); return y* (1-Math.Exp(-t)); }

Voltage across a capacitor (2) Voltage across a capacitor (2)

) 1 ( ) 1 ( 4 ) (

) 1 ( 5 . 5 . t t

e e e t I

− − − −

− − =

= dt t I t Q ) ( ) (

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 V(t) C

C t Q t V ) ( ) ( =

click

slide-56
SLIDE 56

204111 Computer & Programming - Writing Methods

56

Version 2008/1

M M E E

K K I I

Method overloading Method overloading

  • The same method’s name, but not the same set
  • f parameters.
  • System will choose the proper method to call in

accordance with the parameters the caller uses.

static int max(int x, int y) { return (x> y)?x: y; } static double max(double x, double y) { return (x< y)?y: x; } static int max(int a, int b, int c) { if (x> y & x> z) return x; else if (y> x & y> z) return y; else return z; } 1 2 3 4 5 6 7 8 9 10 11

slide-57
SLIDE 57

204111 Computer & Programming - Writing Methods

57

Version 2008/1

M M E E

K K I I

Method overloading (2) Method overloading (2)

  • We cannot overload the method with the same

parameter list, but return the different data type.

  • The sameness

sameness and the difference difference of the parameter list are not considered from the variable’s names used in that parameter list.

static int max(int x, int y) { if (x> y) return x; else return y; } static double max(double x, double y) { if (x> y) return x; else return y; } static int max(int a, int b) { if (a> b) return a; else return b; } 1 2 3 4 5 6 7 8 9 not ok

  • k
slide-58
SLIDE 58

204111 Computer & Programming - Writing Methods

58

Version 2008/1

M M E E

K K I I

Method overloading (3) Method overloading (3)

using System; class myPrint { static void Print(int i) { Console.WriteLine("{0}", i+""); } static void Print(float i) { Console.WriteLine("{0}", i+""); } static void Print(double i) { Console.WriteLine("{0}", i+""); } static void Print(char i) { Console.WriteLine("{0}", i+""); } // ... some more codes public static void Main() { Print(2); Print(2.0f); Print(2/1.0); Print('a'); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22