204111 Computer & Programming
Lecture # 5.2:
Writing Methods
http: / / mike.cpe.ku.ac.th/ 204111
M IKE
TM approved
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 ;
http: / / mike.cpe.ku.ac.th/ 204111
M IKE
TM approved
2
Version 2006/2
M IKE
TM approved
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.
3
Version 2006/2
M IKE
TM approved
class Human { } void Main() { born(); grow(); sick(); } born() { } grow() { } sick() { } dead() { }
How to write a big
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?
4
Version 2006/2
M IKE
TM approved
Think and try to reuse the old codes
Extend from the old codes. Think to use methods provided by the
Console, Math, MessageBox, …
If we need to write a new one, think about
Readability Maintainability Reusability
5
Version 2006/2
M IKE
TM approved
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.
6
Version 2006/2
M IKE
TM approved
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.
7
Version 2006/2
M IKE
TM approved
.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.
8
Version 2006/2
M IKE
TM approved
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 θ
9
Version 2006/2
M IKE
TM approved
⎟ ⎠ ⎞ ⎜ ⎜ ⎝ ⎛ + + + =
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); }
10
Version 2006/2
M IKE
TM approved
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
11
Version 2006/2
M IKE
TM approved
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); }
12
Version 2006/2
M IKE
TM approved
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
13
Version 2006/2
M IKE
TM approved
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
14
Version 2006/2
M IKE
TM approved
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
15
Version 2006/2
M IKE
TM approved
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()
16
Version 2006/2
M IKE
TM approved
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
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.
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 }
18
Version 2006/2
M IKE
TM approved
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
19
Version 2006/2
M IKE
TM approved
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
20
Version 2006/2
M IKE
TM approved
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
21
Version 2006/2
M IKE
TM approved
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 ; }
22
Version 2006/2
M IKE
TM approved
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
not ok
23
Version 2006/2
M IKE
TM approved
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
not ok
24
Version 2006/2
M IKE
TM approved
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 ( . ) (
25
Version 2006/2
M IKE
TM approved
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 ( . ) (
26
Version 2006/2
M IKE
TM approved
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
27
Version 2006/2
M IKE
TM approved
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
28
Version 2006/2
M IKE
TM approved
switch on the circuit.
) 1 ( 5 . 5 . t t
− − − −
V(t) C
= dt t I t Q ) ( ) (
C t Q t V ) ( ) ( =
29
Version 2006/2
M IKE
TM approved
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
30
Version 2006/2
M IKE
TM approved
The same method’s name, but not the same set
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
31
Version 2006/2
M IKE
TM approved
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