390 likes | 629 Views
Chapter 14: Recursion. J ava P rogramming: From Problem Analysis to Program Design, Second Edition. Chapter Objectives. Learn about recursive definitions. Explore the base case and the general case of a recursive definition. Learn about recursive algorithms.
E N D
Chapter 14: Recursion JavaProgramming: From Problem Analysis to Program Design, Second Edition
Chapter Objectives • Learn about recursive definitions. • Explore the base case and the general case of a recursive definition. • Learn about recursive algorithms. • Learn about recursive methods. • Become aware of direct and indirect recursion. • Explore how to use recursive methods to implement recursive algorithms. Java Programming: From Problem Analysis to Program Design, Second Edition
Introduction • // Program prints an array. public class Print { // print array iteratively public static void printIterative( int[] array ) { for (int i=0; i< array.length; ++i ) System.out.print(array[i] + " "); // add ending newline } // end method printArray Java Programming: From Problem Analysis to Program Design, Second Edition
// recursively print array private static void printArrayHelper( int[] array, int startIndex ) { if ( startIndex == array.length ) return; // print elements in normal order System.out.print( array[ startIndex ] + " " ); printArrayHelper( array, startIndex + 1 ); } // end method printArrayHelper Java Programming: From Problem Analysis to Program Design, Second Edition
// recursively print array in reverse order private static void printArrayReverseHelper( int[] array, int startIndex ) { if ( startIndex == array.length ) return; // print elements in reverse order printArrayReverseHelper( array, startIndex + 1 ); System.out.print( array[ startIndex ] + " " ); } // end method printArrayHelper Java Programming: From Problem Analysis to Program Design, Second Edition
public static void main( String args[] ) { int array[] = { 8, 22, 88, 34, 84, 21, 94 }; System.out.print( "Array is: " ); printArrayHelper( array, 0 ); // print array System.out.print( "Array in reverse order is: " ); printArrayReverseHelper( array , 0 );// print array in reverse order } Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Definitions • Recursion: • Process of solving a problem by reducing it to smaller versions of itself. Factorial of an integer: 0! = 1 (14-1) n! = n X (n-1)! If n > 0 (14-2) Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Definitions • Recursive definition: • Definition in which a problem is expressed in terms of a smaller version of itself. • Has one or more base cases. Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Definitions • Recursive algorithm: • Algorithm that finds the solution to a given problem by reducing the problem to smaller versions of itself. • Has one or more base cases. • Implemented using recursive methods. • Recursive method: • Method that calls itself. • Base case: • Case in recursive definition in which the solution is obtained directly. • Stops the recursion. Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Factorial Method public static int fact (int num) { if (num == 0) return 1; else return num * fact(num-1); } Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Factorial Method Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Definitions • General solution: • Breaks problem into smaller versions of itself. • General case: • Case in recursive definition in which a smaller version of itself is called. • Must eventually be reduced to a base case. Java Programming: From Problem Analysis to Program Design, Second Edition
Tracing a Recursive Method Recursive method: • Has unlimited copies of itself. • Every recursive call has its own: • Code • Set of parameters • Set of local variables Java Programming: From Problem Analysis to Program Design, Second Edition
Tracing a Recursive Method • After completing a recursive call: • Control goes back to the calling environment. • Recursive call must execute completely before control goes back to previous call. • Execution in previous call begins from point immediately following recursive call. Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Definitions • Directly recursive: A method that calls itself. • Indirectly recursive: A method that calls another method and eventually results in the original method call.(method A calls method B and method B calls method A) Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Definitions • Tail recursive method: Recursive method in which the last statement executed is the recursive call. • Infinite recursion: The case where every recursive call results in another recursive call. The method will excute until the system runs out of memory Java Programming: From Problem Analysis to Program Design, Second Edition
Designing Recursive Methods • Understand problem requirements. • Determine limiting conditions.( ex:the number of elements in a list) • Identify base cases. Java Programming: From Problem Analysis to Program Design, Second Edition
Designing Recursive Methods • Provide direct solution to each base case. • Identify general cases. • Provide solutions to general cases in terms of smaller versions of general cases. Java Programming: From Problem Analysis to Program Design, Second Edition
Largest Value in Array public static int largest(int[] list, int lowerIndex, int upperIndex) { int max; if(lowerIndex == upperIndex) return list[lowerIndex]; else { max = largest(list, lowerIndex + 1, upperIndex); if(list[lowerIndex] >= max) return list[lowerIndex]; else return max; } } Java Programming: From Problem Analysis to Program Design, Second Edition
Largest Value in Array Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Fibonacci Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Fibonacci public static int rFibNum(int a, int b, int n) { if(n = = 1) return a; else if(n = = 2) return b; else return rFibNum(a, b, n -1) + rFibNum(a, b, n - 2); } Java Programming: From Problem Analysis to Program Design, Second Edition
Recursive Fibonacci Java Programming: From Problem Analysis to Program Design, Second Edition
Recursion or Iteration? • Two ways to solve particular problem: • Iteration • Recursion • Iterative control structures use looping to repeat a set of statements. • Tradeoffs between two options: • Sometimes recursive solution is easier. • Recursive solution is often slower. Java Programming: From Problem Analysis to Program Design, Second Edition
Programming Example: Decimal to Binary Call the remainder of x after division by 2 the right most bit of x. Lets find the binary rep. of 35: Divide 35 by 2. the result is 17 The right most bit of 35 is 1 Divide 17 by 2 = 8 The right most bit of 17 is 1 Divide 8 by 2 = 4 The right most bit of 8 is 0 . . Until the quotient = 0 Java Programming: From Problem Analysis to Program Design, Second Edition
Programming Example: Decimal to Binary The right most bit of 35 cannot be printed until we have printed the right most bit of 17. The right most bit of 17 cannot be printed until we have printed the right most bit of 8, and so on. The binary rep. of 35 = the binary rep. of 17 follwed by the right most bit of 35 The algorithm: binary (num) = num if num = 0 binary (num) = binary(num / 2) followed by num%2 if num > 0 Java Programming: From Problem Analysis to Program Design, Second Edition
Programming Example: Decimal to Binary public static void decToBin(int num, int base) { if(num > 0) { decToBin(num / base, base); System.out.print(num % base); } } Java Programming: From Problem Analysis to Program Design, Second Edition
Programming Example: Decimal to Binary Java Programming: From Problem Analysis to Program Design, Second Edition
Enumeration Types • Java allows programmers to create their own data types by specifying the values of that data type. • These are called enumeration or enum types • They are defined using the key word enum Ex: enum Grades {A, B, C, D, F}; • The values of an enum type are called enumeration or enum constants. • The enum constants within an enum type must be unique. Java Programming: From Problem Analysis to Program Design, Second Edition
Enumeration Types • Each enum type is a special type of class, and the values belonging to the enum type are (special types of) objects of that class. • Grades is a class • A, B, C, D, and F are public static reference variables to objects of the type Grades. Java Programming: From Problem Analysis to Program Design, Second Edition
Enumeration Types • After an enum type is defined you can declare reference variables of that type. • Grades myGrade; • Because each of the variablesA, B, C, D, and F are public static, they can be accessed using the name of the class and the dot operator. myGrade= Grades.B; System.out.println(“myGrade: “ + myGrade); Output: myGrade: B Java Programming: From Problem Analysis to Program Design, Second Edition
Enumeration Types • Ordinal value: a specific value for each enum constant in an enum type. • The ordinal value of the first enum constant is 0, The ordinal value of the second enum constant is 1, and so on. Java Programming: From Problem Analysis to Program Design, Second Edition
Enumeration Types There are some methods associated with enum types: • ordinal(): returns the ordinal value of an enum constant • name(): returns the name of the enum value • values():returns the values of an enum type as a list Java Programming: From Problem Analysis to Program Design, Second Edition
publicclass EnumExample1{enum Grades {A, B, C, D, F}; enum Sports {Baseball, Basketball, Football, Golf, Hockey, Soccer, Tennis}; publicstaticvoid main(String[] args) { Grades myGrade; Sports mySport; myGrade = Grades.A; mySport = Sports.Basketball; System.out.println("Line 8: My grade: " + myGrade); System.out.println("Line 9: The ordinal "+ "value of myGrade is “ + myGrade.ordinal()); System.out.println("Line 10: myGrade name: "+myGrade.name()); System.out.println("Line 11: My sport: " + mySport); System.out.println("Line 12: The ordinal " + "value of mySport is "+mySport.ordinal()); System.out.println("Line 13: mySport name: "+mySport.name()); System.out.println("Line 14: Sports: "); for (Sports sp : Sports.values()) System.out.println(sp + "'s ordinal " + "value is " + sp.ordinal()); System.out.println(); }} Java Programming: From Problem Analysis to Program Design, Second Edition
output Line 8: My grade: A Line 9: The ordinal value of myGrade is 0 Line 10: myGrade name: A Line 11: My sport: Basketball Line 12: The ordinal value of mySport is 1 Line 13: mySport name: Basketball Line 14: Sports: Baseball's ordinal value is 0 Basketball's ordinal value is 1 Football's ordinal value is 2 Golf's ordinal value is 3 Hockey's ordinal value is 4 Soccer's ordinal value is 5 Tennis's ordinal value is 6 Java Programming: From Problem Analysis to Program Design, Second Edition
Enumeration Types enum types can also contain constructors, (private) data members, and methods. • Use the word enum rather than class. • enum types are implicitly final because enum constants should not be modefied. • enum constants are implicitly static. • You can declare reference variables of enum type, but you cannot instantiate objects using he operator new. (the constructors of an enum type are implicitly private) Java Programming: From Problem Analysis to Program Design, Second Edition
Redefining the enum type Grades publicenum Grades{ A ("Range 90% to 100%"), B ("Range 80% to 89.99%"), C ("Range 70% to 79.99%"), D ("Range 60% to 69.99%"), F ("Range 0% to 59.99%");privatefinal String range;private Grades() // or Grades() without the word private { range = ""; }private Grades(String str) // or Grades(String str) { range = str; }public String getRange() {return range; }} Java Programming: From Problem Analysis to Program Design, Second Edition
Example D-3 publicclass EnumExample2{publicstaticvoid main(String[] args) { System.out.println("Grade Ranges"); //Line 1for (Grades gr : Grades.values()) //Line 2 System.out.println(gr + " " + gr.getRange()); //Line 3 System.out.println(); //Line 4 }} Java Programming: From Problem Analysis to Program Design, Second Edition
output Grade Ranges A Range 90% to 100% B Range 80% to 89.99% C Range 70% to 79.99% D Range 60% to 69.99% F Range 0% to 59.99% Java Programming: From Problem Analysis to Program Design, Second Edition