Some methods implemented using recursion can also be directly implemented using iteration.
Example: Iterative implementation of the factorial, exploiting the following iterative definition:
public static long factorialIterative(long n) {
int res = 1;
while (n > 0) {
res = res * n;
n--;
}
return res;
}
Characteristics of the iterative implementation:
Recursive implementation of the factorial, exploiting the recursive definition shown previously:
public static long factorial(long n) {
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
Characteristics of the recursive implementation:
Actually, it is not always possible to implement a recursive method in a simple way without using recursion. However, all recursive methods can be implemented iteratively by simulating recursion through the use of a specific data structure (a stack).