Recursion: a method (function) calls itself : Recursive Method « Class Definition « Java Tutorial






Characteristics of Recursive Methods:

  1. Method calls itself.
  2. When it calls itself, it solves a smaller problem.
  3. There is a smallest problem that the routine can solve it, and return, without calling itself.
public class MainClass {
  public static void main(String[] args) {
    int theAnswer = triangle(12);
    System.out.println("Triangle=" + theAnswer);
  }

  public static int triangle(int n) {
    if (n == 1)
      return 1;
    else
      return (n + triangle(n - 1));
  }
}
Triangle=78








5.10.Recursive Method
5.10.1.Recursion: a method (function) calls itself
5.10.2.The Towers of Hanoi
5.10.3.Recursion: another example
5.10.4.Recursive factorial method
5.10.5.Recursive fibonacci method
5.10.6.Recursive method to find all permutations of a String