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 … ; 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. … ; } } TM approved Version 2006/2 2 M IKE
Write a program with methods class Human { � How to write a big void Main() { program? born(); grow(); � Divide program into sick(); several parts. } � Write each part with a born() { new method. } � Each method has its own grow() { } clear duty to perform. sick() { � Call each method in } Main(), or we can call a dead() { method inside a method? } } TM approved Version 2006/2 3 M IKE
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 TM approved Version 2006/2 4 M IKE
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. TM approved Version 2006/2 5 M IKE
Methods in Math class � All can be used in namespace “System”. � Call with “Math.”, eg., “Math.PI” � Abs(x) : absolute value � Pow(x,y) : x y � Sqrt(x) : square root � Log(x) : natural log (base e) � Exp(x) : e x � Sin(x) : trigonometric sine � Cos(x) : trigonometric cosine � Tan(x) : trigonometric tangent � PI : π � E : e � … Click to see Math member at msdn. TM approved Version 2006/2 6 M IKE
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. TM approved Version 2006/2 7 M IKE
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: (u x ,u y ) and (v x ,v y ). � Calculate the angle between them from ⎛ ⎞ (v x ,v y ) (u x ,u y ) + ⎜ ⎟ u v u v ( )( ) ⎟ θ = − x x y y 1 cos ⎜ + + 2 2 2 2 u u v v ⎝ ⎠ x y x y θ (0,0) � Output the result to stdout. TM approved Version 2006/2 8 M IKE
Write repeated codes into methods ⎛ ⎞ + ⎜ u v u v ⎟ ( )( ) ⎟ θ = x x y y cos( ) ⎜ + + 2 2 2 2 u u v v ⎝ ⎠ x y x y … 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); } TM approved Version 2006/2 9 M IKE
Calculate angles between 2 vectors 1 using System; 2 class AngleBetweenTwoVectors 3 { 4 public static void Main() 5 { 6 double Ux, Uy, Vx, Vy; 7 Ux= ReadInput("Ux"); Uy= ReadInput("Uy"); 8 Vx= ReadInput("Vx"); Vy= ReadInput("Vy"); 9 double cosine = (Ux* Vx + Uy* Vy)/ (length(Ux,Uy) * length(Vx,Vy)); 10 double degree = Math.Acos(cosine) * 180 / Math.PI; 11 Console.WriteLine("Angle between the two vectors is [ { 0} ] .", degree); 12 Console.ReadLine(); 13 } 14 static double ReadInput(string s) / / method ReadInput() 15 { 16 Console.Write("Please enter { 0} : ", s); 17 return Double.Parse(Console.ReadLine()); 18 } 19 static double length(double x, double y) / / method length() 20 { 21 return Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2); 22 } click 23 } TM approved Version 2006/2 10 M IKE
Method structure � Method header � tell us how to use the method. 1 2 � consists of the method property, data type of the result when finished, method name, and parameters it needs. 3 4 � 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); } TM approved Version 2006/2 11 M IKE
Method structure (2) method name method property return data type parameters method static double length(double x, double y) / / method length() header { method return Math.Sqrt(Math.Pow(x,2) + Math.Pow(y,2); body } Return to the caller with the same type of data as declared in the method header TM approved Version 2006/2 12 M IKE
Method header : return data types � Simple data types, eg., int, double, bool, char,… � Class, eg., string, point (discuss later) � Return nothing, ie., void If that method returns static int max(int a, int b) something, we always found it inside another method or on the right int res= max(35, 47); side of assignment operator! static string toString(int i, int radix) string s= toString(10, 16); static void gc() gc(); TM approved Version 2006/2 13 M IKE
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 TM approved Version 2006/2 14 M IKE
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() TM approved Version 2006/2 15 M IKE
Method body 1 using System; 2 class readInt { 3 static void Main() { 4 Console.WriteLine("OUTPUT: { 0} ", readInt()); 5 Console.ReadLine(); 6 } 7 static int readInt() { 8 int x= 0; / / local variable 9 bool success= false; / / local variable 10 do { 11 try { 12 Console.Write(“Type something”); 13 x= int.Parse(Console.ReadLine()); 14 success= true; 15 } catch (Exception e) { 16 Console.WriteLine(e.Message); 17 success= false; 18 } 19 } while (!success); 20 return x; / / return to the caller at line 4 21 } click 22 } TM approved Version 2006/2 16 M IKE
Method body : 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. static long clip(long a) { if (a> 0) return a; else return 0; / / 0 is promoted to 0L } � 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); } TM approved Version 2006/2 17 M IKE
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. 1 static void test(int a) { 2 int z= 7; 3 { int x= z; Console.WriteLine(x); } 4 Console.WriteLine(x); / / wrong 5 { 6 Console.WriteLine(x); / / wrong 7 int x= z; Console.WriteLine(x); 8 { int y= z; Console.WriteLine(y); } 9 { int x= z; Console.WriteLine(x); } / / wrong 10 } 11 } TM approved Version 2006/2 18 M IKE
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. 1 class A { 2 static void Main(string [ ] args) { 3 int s= 0, n= int.Parse(Console.ReadLine()); 4 for(int i= 0; i< = n; i+ + ) { 5 int i2= i* i; 6 s+ = i2; i 7 s,n int i3= i2* i; i2 8 s+ = i3; i3 9 } 10 Console.WriteLine(s); 11 } 12 } TM approved Version 2006/2 19 M IKE
Recommend
More recommend