next up previous
Next: Example: number of occurrences Up: Unit 11 Previous: Example: recursive implementation of

Comparison between recursion and iteration

Some methods implemented using recursion can also be directly implemented using iteration.

Example: Iterative implementation of the factorial, exploiting the following iterative definition:

fact(n) = n . (n - 1) . (n - 2) .   ...   . 2 . 1

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).


next up previous
Next: Example: number of occurrences Up: Unit 11 Previous: Example: recursive implementation of