Вы находитесь на странице: 1из 17

Recursion In JAVA

Mohammad Saad Qureshi 2009-CE-132 Waqas Ahmed 2009-CE-135

Sir Noman Hasny

Sir Syed University Of Engineering & Technology

Recursion
Recursion is the process of defining something in terms of itself. As it relates to Java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive. The classic example of recursion is the computation of the factorial of a number.
// Recursive factorial method. public class FactorialCalculator { // recursive method factorial public long factorial( long number ) { if ( number <= 1 ) // test for base case return 1; // base cases: 0! = 1 and 1! = 1 else // recursion step return number * factorial( number - 1 ); } // end method factorial // output factorials for values 0-10 public void displayFactorials() { // calculate the factorials of 0 through 10 for ( int counter = 0; counter <= 10; counter++ ) System.out.printf( "%d! = %d\n", counter, factorial( counter ) ); } // end method displayFactorials } // end class FactorialCalculator

// Testing the recursive factorial method.


public class FactorialTest { // calculate factorials of 0-10 public static void main( String args[] ) { FactorialCalculator factorialCalculator = new FactorialCalculator(); factorialCalculator.displayFactorials(); } // end main } // end class FactorialTest

Out Put
0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

Fibonacci Series:
Begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers. The Fibonacci series, 0,1,1,2,3,5,8,13,21 The Fibonacci series may be defined recursively as follows: Fibonacci (0) = 0 Fibonacci (1) = 1 Fibonacci (n) = Fibonacci (n-1) + Fibonacci (n-2)

// Recursive fibonacci method.


public class FibonacciCalculator { // recursive declaration of method fibonacci public long fibonacci( long number ) { if ( ( number == 0 ) || ( number == 1 ) ) // base cases return number; else // recursion step return fibonacci( number - 1 ) + fibonacci( number - 2 ); } // end method fibonacci public void displayFibonacci() { for ( int counter = 0; counter <= 10; counter++ ) System.out.printf( "Fibonacci of %d is: %d\n", counter, fibonacci( counter ) ); } // end method displayFibonacci } // end class FibonacciCalculator

// Recursive fibonacci method.


public class FibonacciCalculator { // recursive declaration of method fibonacci public long fibonacci( long number ) { if ( ( number == 0 ) || ( number == 1 ) ) // base cases return number; else // recursion step return fibonacci( number - 1 ) + fibonacci( number - 2 ); } // end method fibonacci public void displayFibonacci() { for ( int counter = 0; counter <= 10; counter++ ) System.out.printf( "Fibonacci of %d is: %d\n", counter, fibonacci( counter ) ); } // end method displayFibonacci } // end class FibonacciCalculator

Out Put
Fibonacci of 0 is: 0 Fibonacci of 1 is: 1 Fibonacci of 2 is: 1 Fibonacci of 3 is: 2 Fibonacci of 4 is: 3 Fibonacci of 5 is: 5 Fibonacci of 6 is: 8 Fibonacci of 7 is: 13 Fibonacci of 8 is: 21 Fibonacci of 9 is: 34 Fibonacci of 10 is: 55

Recursion and Method call stack:The method call stack (also known as the program execution stack) and activation records.

Recursion vs. Iteration:


Both iteration and recursion are based on a control statement: Iteration uses a repetition statement (e.g., for, while or do...while), whereas recursion uses a selection statement (e.g., if, if...else or switch). Iteration and recursion each involve a termination test: Iteration terminates when the loop-continuation condition fails, whereas recursion terminates when a base case is reached. Both iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false, whereas infinite recursion occurs if the recursion step does not reduce the problem each time in a manner that converges on the base case, or if the base case is not tested. To illustrate the differences between iteration and recursion, let us examine an iterative solution to the factorial problem (Fig. 15.10Fig. 15.11). Note that a repetition statement is used (lines 1213 of Fig. 15.10) rather than the selection statement of the recursive solution (lines 912 of Fig. 15.3).

// Iterative factorial method.


public class iterativefact { // recursive declaration of method factorial public long factorial( long number ) { long result = 1; // iterative declaration of method factorial for ( long i = number; i >= 1; i-- ) result *= i; return result; } // end method factorial // output factorials for values 0-10 public void displayFactorials() { // calculate the factorials of 0 through 10 for ( int counter = 0; counter <= 10; counter++ ) System.out.printf( "%d! = %d\n", counter, factorial( counter ) ); } // end method displayFactorials } // end class FactorialCalculator

// Testing the iterative factorial method.


public class IterativeTest { // calculate factorials of 0-10 public static void main( String args[] ) { iterativefact obj = new iterativefact (); obj.displayFactorials(); } // end main } // end class FactorialTest 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

String Permutations:
creating the permutations of a string of textall the different strings that can be created by rearranging the characters of the original string. Words created from these strings are known as anagrams. The permutations for the string "abc" are: abc acb bac bca cab cba

String permutations generated with a recursive method.

// Recursive method to find all permutations of a String. public class Permutation { // recursive declaration of method permuteString public void permuteString( String beginningString, String endingString ) { // base case: if string to permute is length less than or equal to // 1, just display this string concatenated with beginningString if ( endingString.length() <= 1 ) System.out.println( beginningString + endingString ); else // recursion step: permute endingString { // for each character in endingString for ( int i = 0; i < endingString.length(); i++ ) { try { // create new string to permute by eliminating the // character at index i String newString = endingString.substring( 0, i ) + endingString.substring( i + 1 ); // recursive call with a new string to permute // and a beginning string to concatenate, which // includes the character at index i permuteString( beginningString + endingString.charAt( i ), newString ); } // end try catch ( StringIndexOutOfBoundsException exception ) { exception.printStackTrace(); } // end catch } // end for } // end else } // end method permuteString } // end class Permutation

// Testing the recursive method to permute strings.


import java.util.Scanner; public class PermutationTest { public static void main( String args[] ) { Scanner scanner = new Scanner( System.in ); Permutation permutationObject = new Permutation(); System.out.print( "Enter a string: " ); String input = scanner.nextLine(); // retrieve String to permute // permute String permutationObject.permuteString( "", input ); } // end main } // end class PermutationTest

OUT PUT
math maht mtah mtha mhat mhta amth amht atmh athm ahmt ahtm tmah tmha tamh tahm thma tham hmat hmta hamt hatm htma htam

Recursive Backtracking: Our recursive methods all have a similar architecture if the base case is reached, return a result; if not, make one or more recursive calls. In this section we will explore a recursive method that is slightly more complex. This method finds a path through a maze, returning true if there is a possible solution to the maze. The solution involves moving through the maze one step at a time where moves can be made by going down, right, up or left (diagonal moves are not permitted). From the current location in the maze (starting with the entry point), the following steps are taken: A direction is chosen, the move is made in that direction and a recursive call is made to solve the remainder of the maze from the new location. When a dead end is reached (i.e., we cannot take any more steps forward without hitting a wall), we back up to the previous location and try to go in a different direction. If there is no other direction that can be taken, we back up again. This process continues until we find a point in the maze where a move can be made in another direction. Once such a location is found, we move in the new direction and continue with another recursive call to solve the rest of the maze.

To back up to the previous location in the maze, our recursive method simply returns false, moving up the method-call chain to the previous recursive call (which references the previous location in the maze). This process of using recursion to return to an earlier decision point is known as recursive backtracking. If one set of recursive calls does not result in a solution to the problem, the program backs up to the previous decision point and makes a different decision, often resulting in another set of recursive calls. In this example, the previous decision point is the previous location in the maze, and the decision to be made is the direction that the next move should take. One direction has led to a dead end, so the search continues with a different direction. Unlike our other recursive programs, which reached the base case and then returned all the way up the method-call chain to the original method call, the recursive backtracking solution to the maze problem uses recursion to return only part of the way up the method-call chain, then try a different direction. If the backtracking reaches the entry location of the maze and the paths in all directions have been attempted, the maze does not have a solution.

Вам также может понравиться