Recursion

Recursion is when a method calls itself to solve a problem.
A recursive method breaks a big problem into smaller versions of the same problem.

Every recursive method must have:

  1. A base case (stops the recursion)

  2. A recursive call (reduces the problem)

If either part is missing, the recursion will run forever.

public int method(int n) {

if (n == 0) {

return 1; // base case

} else {

return n * method(n - 1); // recursive call

}

}

The base case stops the recursion.
It prevents infinite loops and stack overflow.

The recursive call must move toward the base case.

Example:

return n * method(n - 1);

If the recursive call does not get closer to the base case, the recursion never ends.