5. 10. 1. Recursion: a method (function) calls itself |
|
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 |