What is Recursion? Recursion Vs. Iteration

J.E.D.I. 3 Advanced Programming Techniques

3.1 Objectives

This module introduces some advanced programming techniques. You will learn about recursion and abstract data types in this section. After completing this lesson, you should be able to: 1. Define and apply recursion in programming 2. Differentiate between stacks and queues 2. Implement sequential implementation of stacks and queues 3. Implement linked implementation of stacks and queues 4. Use existing Collection classes

3.2 Recursion

3.2.1 What is Recursion? Recursion is a powerful problem-solving technique that can be applied when the nature of the problem is repetitive. Indeed, this type of problems are solvable using iteration i.e., using looping constructs such as for, while and do-while. In fact, iteration is a more efficient tool compared to recursion but recursion provides a more elegant solution to the problem. In recursion, methods are allowed to call upon itself. The data passed into the method as arguments are stored temporarily onto a stack until calls to the method have been completed.

3.2.2 Recursion Vs. Iteration

For a better understanding of recursion, let us look at how it varies from the technique of iteration. Handling problems with repetitive nature using iteration requires explicit use of repetition control structures. Meanwhile, for recursion, the task is repeated by calling a method repetitively. The idea here is to define the problem in terms of smaller instances of itself. Consider computing for the factorial of a given integer. It’s recursive definition can be described as follows: factorialn = factorialn-1 n; factorial1 = 1. For example, the factorial of 2 is equal to the factorial12, which in turn is equal to 2. The factorial of 3 is 6, which is equal to the factorial23. Introduction to Programming II Page 40 J.E.D.I. Figure 3.1: Factorial Example With iteration, the process terminates when the loop condition fails. In the case of using recursion, the process ends once a particular condition called the base case is satisfied. The base case is simply the smallest instance of the problem. For example, as seen in the recursive definition of factorial, the simplest case is when the input is 1. 1 for this problem is the base case. The use of iteration and recursion can both lead to infinite loops if these are not used correctly. Iteration’s advantage over recursion is good performance. It is faster compared to recursion since passing of parameters to a method causes takes some CPU time. However, recursion encourages good software engineering practice because this technique usually result in shorter code that is easier to understand and it also promotes reusability of a previously implemented solution. Choosing between iteration and recursion is a matter of balancing good performance and good software engineering.

3.2.3 Factorials: An Example