204111 Computer & Programming Lecture # 5.2: Writing Methods - - PowerPoint PPT Presentation

204111 computer programming
SMART_READER_LITE
LIVE PREVIEW

204111 Computer & Programming Lecture # 5.2: Writing Methods - - PowerPoint PPT Presentation

204111 Computer & Programming Lecture # 5.2: Writing Methods http: / / mike.cpe.ku.ac.th/ 204111 TM approved M IKE Why we need to write methods? class Human { Long main program is void Main() { hard to read and ;


slide-1
SLIDE 1

204111 Computer & Programming

Lecture # 5.2:

Writing Methods

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

M IKE

TM approved

slide-2
SLIDE 2

2

Version 2006/2

M IKE

TM approved

Why we need to write methods?

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

Long main program is

hard to read and

understand,

hard to debug, hard to improve or update.

Normally, a (big) program

can be divided into several

sub-programs, each has its own clear duty.

has some parts that must

be performed repeatedly.

slide-3
SLIDE 3

3

Version 2006/2

M IKE

TM approved

Write a program with methods

class Human { } void Main() { born(); grow(); sick(); } born() { } grow() { } sick() { } dead() { }

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?

slide-4
SLIDE 4

4

Version 2006/2

M IKE

TM approved

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-5
SLIDE 5

5

Version 2006/2

M IKE

TM approved

Methods we’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-6
SLIDE 6

6

Version 2006/2

M IKE

TM approved

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-7
SLIDE 7

7

Version 2006/2

M IKE

TM approved

Example of 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-8
SLIDE 8

8

Version 2006/2

M IKE

TM approved

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.

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

( )( )⎟

⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + + =

− 2 2 2 2 1

cos

y x y x y y x x

v v u u v u v u θ

slide-9
SLIDE 9

9

Version 2006/2

M IKE

TM approved

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-10
SLIDE 10

10

Version 2006/2

M IKE

TM approved

Calculate angles between 2 vectors

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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

slide-11
SLIDE 11

11

Version 2006/2

M IKE

TM approved

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.

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

slide-12
SLIDE 12

12

Version 2006/2

M IKE

TM approved

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-13
SLIDE 13

13

Version 2006/2

M IKE

TM approved

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!
slide-14
SLIDE 14

14

Version 2006/2

M IKE

TM approved

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 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-15
SLIDE 15

15

Version 2006/2

M IKE

TM approved

Method header : parameters

Treat as local variables that can only be used in

that method.

Each parameter is written in the same way as

variable declaration, one by one, but no semi- colon at the end.

Each parameter is separated by 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-16
SLIDE 16

16

Version 2006/2

M IKE

TM approved

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-17
SLIDE 17

17

Version 2006/2

M IKE

TM approved

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, when we have nothing to return to the caller.

Method body : return

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-18
SLIDE 18

18

Version 2006/2

M IKE

TM approved

Method body : 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-19
SLIDE 19

19

Version 2006/2

M IKE

TM approved

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-20
SLIDE 20

20

Version 2006/2

M IKE

TM approved

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

no return statement no return type defined missing type declaration duplicate declaration returning double instead

  • f float
slide-21
SLIDE 21

21

Version 2006/2

M IKE

TM approved

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-22
SLIDE 22

22

Version 2006/2

M IKE

TM approved

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-23
SLIDE 23

23

Version 2006/2

M IKE

TM approved

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-24
SLIDE 24

24

Version 2006/2

M IKE

TM approved

Integration using mid-point rule

Divide the area under curve into many small

rectangles.

Sum those areas using the mid-point rule.

x0 x1 x2 xn f(x)

n a b h − =

∑ ∫

= − +

n i i i b a

x x f h dx x f

1 1

) 2 ( . ) (

slide-25
SLIDE 25

25

Version 2006/2

M IKE

TM approved

Integration using mid-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-26
SLIDE 26

26

Version 2006/2

M IKE

TM approved

Integration using Simpson’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-27
SLIDE 27

27

Version 2006/2

M IKE

TM approved

Integration using Simpson’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-28
SLIDE 28

28

Version 2006/2

M IKE

TM approved

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

− − − −

− − =

V(t) C

= dt t I t Q ) ( ) (

C t Q t V ) ( ) ( =

slide-29
SLIDE 29

29

Version 2006/2

M IKE

TM approved

Voltage across a capacitor (2)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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)); } V(t) C ) 1 ( ) 1 ( 4 ) (

) 1 ( 5 . 5 . t t

e e e t I

− − − −

− − =

= dt t I t Q ) ( ) ( C t Q t V ) ( ) ( =

click

slide-30
SLIDE 30

30

Version 2006/2

M IKE

TM approved

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-31
SLIDE 31

31

Version 2006/2

M IKE

TM approved

Method overloading (2)

We cannot overload the method with the same parameter

list, but return the different data type.

The sameness and the 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