Java Reference
In-Depth Information
Most modern compilers will convert certain simple recursive method definitions to
iterative ones before running the program. A method that uses tail recursion has the
property that it does nothing after the recursive call except return the method's value.
In this case, a tail recursive method can be easily converted to an equivalent iterative
solution. This operation may be performed by the compiler or by the JVM.
tail
recursion
Self-Test Exercise
15. Write a recursive method defi nition for the following method:
/**
Precondition: n >= 1
Returns the sum of the squares of the numbers 1 through n.
*/
public static int squares( int n)
For example, squares(3) returns 14 because 1 2 + 2 2 + 3 2 is 14.
EXAMPLE: Finding a File
The next program is an example where a recursive solution is much easier to write
and understand than an iterative solution. Consider the problem of finding a file
buried somewhere in your file system. For example, using the Windows file system,
let's say that you have the following file and directory structure on your hard drive:
Display 11.10
Sample File System Structure
C:\
JavaPrograms\
Recursion\
FindFile.java
BinarySearch.java
Homework\
Homework1.java
Homework2.java
Test.java
Papers\
TermPaper.odt
Workfile.docx
Letter.txt
 
Search WWH ::




Custom Search