What is recursion and why is it useful?

Recursion is when a named block of code (a subroutine or function) calls itself. We can use recursion to describe some algorithms in very few lines. For example, the following block of pseudocode will recursively print out the numbers less than 10 in the Fibonacci sequence:
function fibonacci (int n, int m, int max) { int sum = n+m; if (sum <= max) { print (sum); fibonacci (m, sum, max); } } fibonacci (0, 1, 10);
This algorithm is recursive because inside the fibonacci function we can see a call to the fibonacci function. This will itself call the fibonacci function and so on until one of these calls fails the check in the if statement and runs to the end of the function instead. In all cases where recursion is a viable solution, a loop will also do the job (try to rewrite the above code with a while loop instead!). Often loops are better as they don't hog resources (e.g. memory) like recursion tends to do. So why would you ever use recursion? Sometimes (in very simple programming languages) we do not have loops and so recursion is the only way to loop code at all, but sometimes recursive code is just easier to read and understand than the equivalent loop. Writing code that is easy to understand is one of the most important things to think about when programming (second only to making sure your code is actually working!).

Answered by John W. Computing tutor

1619 Views

See similar Computing A Level tutors

Related Computing A Level answers

All answers ▸

What is the difference between interpreted and intermediate code?


Show how the decimal number -183 would be represented as an 8-bit two's complement arithmetic


How to represent a negative decimal number using 8-bit binary two's complement ?


Some problems are intractable. What does it mean for a problem to be described as intractable?


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo
Cookie Preferences