Recursion: a method (function) calls itself : Recursive Method « Class Definition « Java Tutorial
- Java Tutorial
- Class Definition
- Recursive Method
Characteristics of Recursive Methods:
- Method calls itself.
- When it calls itself, it solves a smaller problem.
- 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