Recursion+Class+Notes 1
Recursion+Class+Notes 1
Recursion is the process of calling one's self, that is, inside a method the method
calls
itself. For example:
The base condition is when the recursion terminates, when the method stops
calling itself.
The recursive calling must stop at some point, otherwise you will have an infinite
recursion (like an infinite loop).
There must be some pattern that is repeated that can be reproduced in the code.
For example to write a recursive method to compute the factorial of a number
(4! =4•3•2•1), we define the base case:
What are the two things we need to have to make a recursive algorithm?
b. z = add(0);
c. z = add(10);
How many times will the method be called with the following statement?
z = add(100);
Find and correct the errors in the following recursive method that
returns the sum of the integers from a to b inclusively. Give a
precondition for this method so that it will work as intended.
}
The following Java program contains a recursive method for reversing a String.
Describe the problem of reversing a String using recursion?
import java.util.*;
public class StringReverse {
/**
* Linear recursive string reversal
*
* Reverses the whole string except the first character, then concatenates the reversed
* string and the first character. Requires n method calls
*/
public static String linearStringReverse(String x){
if(x.length() == 1){
return x;
}
return linearStringReverse( x.substring(1) ) + x.charAt(0);
}
The following diagram illustrates the recursive function for reversing a String:
Recursion Animations
http://www.animatedrecursion.com