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:

• initialization:
Ex. res = 1;
• loop operation, executed a number of times equal to the number of repetitions of the loop:
Ex. res = res * n;
• termination:
Ex. n--; allows the condition (n > 0) of the while loop to become false

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:

• base step:
Ex. return 1;
• recursive step:
Ex. return n * factorial(n-1) ;
• termination is guaranteed by the fact that the recursive call factorial(n-1) decreases by one the value passed as parameter; hence, if initially we have n>0, sooner or later we reach an activation in which the condition n==0 is true and hence only the code for the base step is executed.

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: Example: number of occurrences Up: Unit 11 Previous: Example: recursive implementation of