Practice Problem # 1 - Recursion 1
Practice Problem # 1 - Recursion 1
Recursion
Recursion is the process of defining a function to call itself using smaller inputs. A function that uses
recursion is called a recursive function. As an example, consider the factorial function, 𝑛! defined
to be 1 × 2 × 3 × 4 × … × 𝑛. This function can easily be implemented as a for-loop statement, but it
can be defined as a function 𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(𝑛):
𝑛 × 𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(𝑛 − 1) 𝑛 > 1
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(𝑛) = {
1 𝑛=1
The computation of 𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(5) is shown below:
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(5) = 5 ∗ 𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(4)
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(4) = 4 ∗ 𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(3)
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(3) = 3 ∗ 𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(2)
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(2) = 2 ∗ 𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(1)
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(1) = 1
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(2) = 2 ∗ 1 = 2
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(3) = 3 ∗ 2 = 6
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(4) = 4 ∗ 6 = 24
𝑓𝑎𝑐𝑡𝑜𝑟𝑖𝑎𝑙(5) = 24 ∗ 5 = 120
This function can be implemented in Java:
public int factorial(int n){
if(n==1) return 1
return n * factorial(n-1);
}
A recursive function has two major parts - the base case and the recursive case. The base case
returns a result without recursion when the input is small enough that it can be computed directly.
The base case in the factorial function is the part that computes the factorial function for 𝑛 = 1. The
recursive case is the part where recursive calls are made. It also includes procedures for combining
results from each recursive calls.
In tail recursion, the only step after doing the recursion is to return the output.
DCIT25 February 4, 2020
Problems that can be solved using loop statements can be solved using recursion. Execute and
analyze the following:
Printing the First 𝒏 Positive Integers
Idea: If 𝑛 = 1 then print 1. Otherwise, print the first 𝑛 − 1 positive integers recursively then print
𝑛.
The first sum() function that takes only one input is a helper function (this is not the recursive
function) to call the recursive sum() function (the other sum function that takes 2 inputs) with the
correct initial values. This strategy is common with recursive functions.
Computing the sum can be written as tail recursive:
Self-Test
2. Create a recursive function that takes as input an array 𝐴 of positive integers and a number
𝑑 then prints all numbers in 𝑎 divisible by 𝑑, one line at a time.
3. Create a recursive function that returns the index of element 𝑥 in the array 𝐴 if 𝑥 is in the array,
otherwise it returns -1. Hint: If 𝑥 is in the array then it is either the first element or some other
element after the first element.
5. Create a recursive function that takes an array of characters then print all possible pairs of
characters in the array, one line at a time.