Recursion (OCR A Level Computer Science)

Revision Note

Last updated

Features of Recursion

What is Recursion?

  • Recursion is a highly effective programming technique where a function calls itself to solve a problem or execute a task

  • Recursion doesn't rely on iterative loops. Instead, it uses the idea of self-reference to break down complicated problems into more manageable subproblems

  • A recursive algorithm has three features:

    • the function must call itself

    • a base case - this means that it can return a value without further recursive calls

    • a stopping base - this must be reachable after a finite number of times

How does recursion work?

  • In a recursive function, the function calls itself with a modified input parameter until it reaches a base case — a condition that stops the recursion and provides the final result

  • Each recursive call breaks down the problem into more minor instances until it reaches the base case

Example: Factorial calculation

def factorial(n):

# Base case

    if n == 0 or n == 1:

       return 1

    else:

      # Recursive call with a smaller instance of the problem

        return n * factorial(n - 1)

result = factorial(5)

print(result)

# Output: 120 (5! = 5 * 4 * 3 * 2 * 1)

  • In this example, the factorial function calculates the factorial of a positive integer n

  • It does so by breaking down the problem into smaller instances, multiplying n with the factorial of (n - 1) until it reaches the base case (n == 0 or n == 1)

Importance of a proper stopping condition

  • It is important to have a proper stopping condition or base case when using recursion to avoid stack overflow errors which result in program crashes

  • If a recursive function does not have a stopping condition, it will continue to call itself indefinitely, which can use up excessive memory and cause the program to malfunction

Designing a stopping condition

  • When creating a stopping condition, it's important to consider the problem being solved

  • Identify the easiest scenario where the function can provide a direct result. This scenario should be defined as the base case, covering the simplest instances of the problem

  • By doing so, the function will be able to stop the recursion when those conditions are met

  • The difference between line 7 and the function declaration on line 1, is that num1 is replaced with result + 1 so we'll need to set num1 equal to result + 1

Recursion: Benefits & Drawbacks

  • Programs can be written using either recursion or iteration - which one is used will depend on the problem being solved

  • There are many benefits and drawbacks to using either, depending on the situation:

Recursion

Benefits

Drawbacks

Concise - can often be expressed in a more concise way, especially for structures like trees or fractals

Performance - repeated function calls can be CPU and Memory intensive, leading to slower execution

Simple - simply stating what needs to be done without having to focus on the how can make it more readable and maintainable

Debugging - recursive code can be much more difficult to track the state of the program

 

Limited application - not all problems are suited to recursive solutions

Iteration

Benefits

Drawbacks

Performance - more efficient that recursion, less memory usage. 

Complexity - can get very complex and use more lines of code than recursive alternatives

Debugging - easier to understand and debug

Less concise - compared to recursive alternatives, making them harder to understand

Wider application - more suitable to a wider range of problems

 

Writing Recursive Algorithms

  • Here is a recursive algorithm for a simple countdown program written in Python to countdown from 10 to 0

Step 1

  • Create the subroutine (in this example it will be a function as it will return a value) and identify any parameters

def countdown_rec(n): #n is the parameter passed when we call the subroutine

Step 2

  • Create a stopping condition - when n is 0 the function will stop

def countdown_rec(n):

   print(n) #output the starting number
   if n == 0: #stopping condition
      return

Step 3

  • Add a recursive function call

def countdown_rec(n):
    print(n)
    if n == 0:
        return
    countdown_rec(n -1) #recursive functional call

Step 4

  • Call the function

def countdown_rec(n):
    print(n)
    if n == 0:
        return
    countdown_rec(n -1)

countdown_rec(10) #call the function and pass 10 as a starting value

Output to user

10
9
8
7
6
5
4
3
2
1
0

Tracing Recursive Algorithms

  • Now lets trace the recursive algorithm we have just written to check what happens during the execution of the program

  • Here is the completed program and we are going to start it using the command countdown_rec(5)

 def countdown_rec(n):
    print(n)
    if n == 0:
        return
          countdown_rec(n -1)

  • Using a simple trace table we can trace the recursive function call

Function call

print(n)

countdown_rec(n -1)

countdown_rec(5)

5

4

countdown_rec(4)

4

3

countdown_rec(3)

3

2

countdown_rec(2)

2

1

countdown_rec(1)

1

0 (return)

Translate Between Iteration & Recursion

  • Recursive algorithms can be translated to use iteration, and vice versa

  • Let's look at the previous example recursive program and see how it would change to solve the same problem but using an iterative approach

Recursive approach

01 def countdown_rec(n):
02    print(n)
03    if n == 0:
04        return
05    countdown_rec(n -1)
06 countdown_rec(10)

Iterative approach

01 def countdown_rec(n):
02   while n > 0:
03     print(n)
04     n = n-1
05   return
06 countdown_rec(10)

  • The recursive function call on line 05 has been replaced with a while loop (line 02) which checks if n > 0

  • Using an iterative approach we use exactly the same amount of code (6 lines) BUT...

    • less memory would be used (increased performance)

    • easier to debug

Worked Example

Hugh has written a recursive function called thisFunction() using pseudocode.

01 function thisFunction(theArray, num1, num2, num3)
02    result = num1 + ((num2 - num1) DIV 2)
03    if num2 < num1 then
04       return -1
05    else
06       if theArray[result] < num3 then
07          return thisFunction(theArray, result + 1, num2, num3)
08       elseif theArray[result] > num3 then
09          return thisFunction(theArray, num1, result - 1, num3)
10       else
11          return result
12       endif
13    endif
14 endfunction

Rewrite the function thisFunction() so that it uses iteration instead of recursion.
You should write your answer using pseudocode or program code.

6 marks

How to answer this question:

  • The lines which call the function recursively are lines 07 and 09 so these are the lines which need to be changed

  • To ensure the code is repeated, we can put lines 02 to 13 in a while loop:

while true

  • The difference between line 07 and the function declaration on line 01, is that num1 is replaced with result + 1 so we'll need to set num1 equal to result + 1

num1=result+1

  • The difference between line 9 and the function declaration on line 1, is that num2 is replaced with result - 1 so we'll need to set num2 equal to result - 1

num2=result-1

  • All other lines of code remain the same

Answer:

function thisFunction(theArray, num1, num2, num3)

   while (true)

      result = num1 + ((num2 - num1) DIV 2)

      if num2 < num1 then

         return -1

      else

         if theArray[result] < num3 then

            num1 = result + 1

         elseif theArray[result] > num3 then

            num2 = result - 1

         else

            return result

         endif

      endif

   endwhile

endfunction

Examiner Tips and Tricks

Some questions will ask you to write an answer in pseudocode, whereas others will ask for pseudocode or program code. If it says you can write in program code, you can write in a language you choose, e.g. Python or Java. You won't be asked to name the language but do use the syntax from the language you're using if you're not using pseudocode

You've read 0 of your 10 free revision notes

Unlock more, it's free!

Join the 100,000+ Students that ❤️ Save My Exams

the (exam) results speak for themselves:

Did this page help you?