Recursion
15-111
Advanced Programming
Ananda Gunawardena
June 05, 2007
04/17/24 1
Recursion
• A recursive function is a function that calls itself
either directly, or indirectly through another
function; it is an alternative to iteration
• A recursive solution is generally less efficient in
terms of system overhead, due to the overhead of
extra function calls; however recursive functions
– allow us to think of solutions to problems that may be
recursive in nature
– allow us to work with data structures that are best
accessed recursively
04/17/24 2
Recursion
• A recursive problem
Imagine a computer environment that does not
support the multiplication operator (*), but it does
support addition (+)
• Define multiplication as follows
Multiply(m,n) = m if n=1
= m + Multiply(m,n-1) otherwise
04/17/24 3
Multiplication using the +
operator
public int multiply (int m, int n)
// IN: m and n, values to be multiplied
// PRE: m and n are defined and n > 0
// POST: returns m * n
// RETURNS: Product of m * n if n is positive;
otherwise, returns m
{
if (n <= 1)
return m;
else
return m + multiply (m, n - 1);
}
04/17/24 4
Tracing the code
• Multiply(4,3)
04/17/24 5
General Form of a recursive Function
• The recursive functions we work with will generally consist of an if
statement with the form shown below
if the stopping case or base case is reached
solve the problem
else
reduce the problem using
recursion
04/17/24 6
What problems can be solved using
Recursion
• Problems that lend themselves to recursive solution
have the following characteristics
– one or more simple cases of the problem
(stopping cases) have a straightforward, non-
recursive solution
– For the other cases, there is a process (using
recursion) for substituting one or more reduced
cases of the problem closer to a stopping case
– Eventually the problem can be reduced to
stopping cases only
04/17/24 7
Factorial Function
04/17/24 8
Thinking about Lists recursively
• A list can be defined recursively
• A list is either empty or the first element of the
list followed by another list (called tail of the list)
– L = Ф or
– L = {first(L), tail(L)}
04/17/24 9
List Operations
• Prepend
– prepend(a,L) = {a} if L= Ф
– prepend(a,L) = {a, prepend(first(L), tail(L))}
• Append recursively
– Append(L, a) = {a} if L= Ф
– Append(L, a) = prepend(first(L),Append(tail(L), a))
04/17/24 10
Length of a list recursively
• Length(L) = 0 if L = Ф
• Otherwise
– Length(L) = 1 + length(tail(L))
04/17/24 11
Reversing a list
• Rev(L) = L if L = Ф
• Rev(L) = append(first(L), Rev(tail(L));
04/17/24 12