CT 229 Methods Continued 13/10/2006 CT229
Lab Assignments Due Date for current lab assignment : Oct 20 th In Part 1 of Assignment you can declare a constant 3.14 to use as PI or you can use Math.PI Formula for converting from Celsius to Fahrenheit F = 9/5 (C+32) Before submission make sure that the name of each.java file matches the name given in the assignment sheet!!!! Remember: Electronic Submission @ http://ecrg-vlab01.it.nuigalway.ie/uploader/submissions.html 13/10/2006 CT229 1
Review of Last Week- Loops Loops While Loops Do/While Loops For Loops Different methods for initialising and incrementing the control variable in a for loop Nested For Loops 13/10/2006 CT229 2
Review of Last Week- Methods Format: method-type return-type method-name (parameter-list) declarations and statements: body of method Passing Parameters Returning a Value from a Method Scope of Variables in a Method 13/10/2006 CT229 3
More About Parameters When a variable is an argument in calling a method: The argument variable does not have to have the same name as the corresponding parameter! The parameter in the same position is given the value of the argument variable Simple variables are passed by value: the method just gets a copy of the value; they are not made equivalent If you change the value in the method, the original value of the variable is not changed int n = 5; public static void noeffect(int x) noeffect(n); System.out.println ("n is now " + n); x = x * 3; // Prints: n is now 5 // HAS NO EFFECT! 13/10/2006 CT229 4
Example of Variable Scope public static void main(string[] args) int num = 5; Value of num is 6 Value of num is 5 printoutvalues(num); System.out.println("Value of num is "+num); public static void printoutvalues(int num) num++; System.out.println("Value of num is "+num); 13/10/2006 CT229 5
Return Values Methods must return a value of the appropriate type Unless declared to be void Done with a return statement Often last statement in method, but can occur anywhere Can have multiple return statements Same rules as for parameters: For primitive data types, a value is returned The value returned may be used in an assignment or other expression in the calling method 13/10/2006 CT229 6
Introduction to Overloading Problem Scenario Consider a simple method that prints out a textual representation of its argument. This method should be able to print out an int, double, boolean or String. You could create four separate methods public static void printint(int num) public static void printdouble(double num), public static void printboolean(boolean condition) public static void printstring(string words) However now a user has to remember the name of each method when they want to print out a value. It would be much easier from a users perspective to call a single method (println) that would print out whatever value you pass it (whether it be an int, double, boolean or String) 13/10/2006 CT229 7
Introduction to Overloading int intnum = 2; double doublenum = 2.3; boolean test = true; String sample = "Hello World"; System.out.println(intNum); System.out.println(doubleNum); System.out.println(test); System.out.println(sample); 2 2.3 true Hello World Notice that the method println is capable of taking in an int parameter, a double parameter, a boolean parameter and a String parameter!!!! 13/10/2006 CT229 8
Overloading (1) Sometimes, you need methods that perform similar operations for different data types would like to use the same name e.g. println(int) / println(float) / println(string) Method Overloading: Java allows different methods of the same name to be defined, as long as they have different parameter lists The signature of each method must be unique Method Signature: Name of method + data types of parameters, in given order: fn(int) / fn(float) / fn(int, String) 13/10/2006 CT229 9
Example of Overloading public static void main(string[] args) double doublenum = 5.2; int intnum = 6; System.out.println( triple( doublenum ) ); System.out.println( triple( intnum) ); public static int triple(int num) return (num *= 3); 15.6 18 public static double triple(double num) Also See: Overloading.java return (num *= 3); 13/10/2006 CT229 10
Overloading (2) Basic principle: The compiler must be able to determine unambiguously which version of method to call Return value not considered: you cannot define two methods that differ only in return value Names of parameters not considered: Compiler could not determine from method call which one is intended 13/10/2006 CT229 11
Recursion Methods can call other methods, but can also call themselves Directly; or indirectly via another method This creates a form of loop: termed recursion Like other loops, recursive methods have to be carefully constructed so that they terminate correctly A small but significant number of problems can be solved elegantly this way 13/10/2006 CT229 12
Recursion MethodA MethodA MethodA MethodA 13/10/2006 CT229 13
Recursion Problem You probably see one problem with recursion. Where does it end? When you write recursive methods you have to be careful to include stopping conditions. This is called a base condition Although Java doesn't put any particular limits on the depth to which you can expand a recursion, it is very possible to have a run-away recursion eat up all the memory in your computer. 13/10/2006 CT229 14
Recursion A recursive method must have: 1. Test to stop or continue the recursion 2. A base case that terminates the recursion 3. Recursive call(s) that continue the recursion 13/10/2006 CT229 15
Consider this Simple For Loop public static void main(string[] args) final int num1 =4; int total = 0; The total is 10 for (int i = num1; i > 0; i--) total += i; System.out.println("Total is "+10); 13/10/2006 CT229 16
Easiest Recursion Program Ever!! public static void main(string[] args) int num = 4; int total = summation(num); System.out.println("Total is "+total); The total is 10 public static int summation(int num) if (num == 1) Test Base Case else return 1; return ( num + summation(num-1) ); Recursive Call 13/10/2006 CT229 17
Solving Factorial using Recursion Consider the following example Facorial (!) 5! = 5 * 4 * 3 * 2 * 1 How would you implement this using a recursion?? 13/10/2006 CT229 18
Factorial using Recursion factorial( 5 ) = 5 * factorial( 4 ) = 5 * ( 4 * factorial( 3 ) ) = 5 * ( 4 * (3 * factorial( 2 ) ) ) = 5 * ( 4 * (3 * (2 * factorial( 1 ) ) ) ) = 5 * ( 4 * (3 * (2 * ( 1 * factorial( 0 ) ) ) ) ) = 5 * ( 4 * (3 * (2 * ( 1 * 1 ) ) ) ) = 5 * 4 * 3 * 2 * 1 * 1 = 120 13/10/2006 CT229 19
Recursive Factorial This can be summed up as N! = N * (N-1)! Assume factorial is the name of the method we will use in our java program factorial( N ) = N * factorial( N-1 ) How should it end (Base Case)? factorial(0) = 1 13/10/2006 CT229 20
Recursive Factorial public static int factorial( int num ) if ( num == 0 ) return 1; else return num * factorial(num -1) ; 13/10/2006 CT229 21
Recursion Another Example: Fibonacci numbers for a mathematical sequence that can be defined recursively as: See: Fibonacci.java => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233. Notice after two starting values, each number is the sum of the two preceding numbers 13/10/2006 CT229 22
Recursive Fibonacci public static int fibonacci(int n) if (n == 0) return 0; else if (n == 1) return 1; else return fibonacci(n-1) + fibonacci(n-2); 13/10/2006 CT229 23
Fibonacci 13/10/2006 CT229 24
Recursion (2) Iteration can be used anywhere you can use recursion Sometimes recursion is more elegant, if it reflects the way the problem is usually thought about Aim to use most intuitive representation of problems public static int factorial( int num) int product = 1; for ( int j=1; j<=num; j++ ) product *= j; return product; 13/10/2006 CT229 25
Drawbacks of Recursion Drawbacks of recursion: Inefficient use of resources: large amount of deeply nested method calls to be kept track of together Number of calls can explode: f(20) takes 21,891 calls to method f(30) takes 2,692,537 calls Depending on algorithm, can involve re-computing values that were already computed Normal loops can avoid these problems 13/10/2006 CT229 26