The Code that Calls Itself…and Itself…and Itself…đ
Letâs say someone got you a gift and they handed you this huge wrapped-up box that required all your strength to hold. You then start to unwrap this gift and soon realise that inside this gift-wrapped box is another…gift-wrapped boxâŚyou continue to unwrap this smaller box and once youâre done, you realise thereâs another even smaller gift-wrapped box inside it. This goes on for three more boxes (getting smaller and smaller) until you finally reach the gift (imagine that ideal item youâve been longing to have or own for ages). Thatâs recursion! Youâre solving a bigger problem by breaking it down into smaller problems until you reach the simplest one.
We just described the concept of recursion using a metaphor of unwrapping nested gift boxes. The initial large wrapped box represents the original problem. The act of unwrapping it to reveal another gift-wrapped box inside represents a recursive function calling itself to solve a smaller sub-problem. The process continues until a base case is reached, which is symbolised by the smaller gift box that contains the desired gift. In the context of C programming, it represents a recursive function that calls itself repeatedly until it reaches a base case.
The image above depicts an illustration of Recursion.
Introduction
Recursion is a fundamental concept in Computer Science and programming that allows a function or method to call itself within its own definition. In this post, we will explore what recursion is, how to implement it, and when it should and should not be used.
What is Recursion?
Recursion is a programming technique that involves a function or method calling itself within its own definition. The idea behind recursion is to break a problem down into smaller and smaller sub-problems until they are simple enough to solve. Each time the function is called, it works on a smaller and simpler version of the original problem until the base case is reached.
The base case is the condition in which the function does not call itself again and returns a value. The base case is essential because, without it, the function would continue to call itself indefinitely, resulting in an infinite loop and eventually crashing the program.
How to implement Recursion
To implement recursion in a program, you need to define a function or method that calls itself within its own definition. To gain a better understanding of recursion, suppose we wanted to calculate the factorial of a number using recursion.
Note âđź: The factorial of a number is the product of all positive integers less than or equal to that number.
| |
What does all this mean? â Let’s walk through the above function step-by-step:
- First, include the standard libraries
#include <stdio.h>required to use built-in functions likeprintf. - Then we include the function description, stating the name and purpose of the function as well as any parameters in use.
- We declare a recursive function called
factorialthat takes an integernas a parameter and returns an integer. - Inside the
factorialfunction, we have the base case. Ifnis 0 or 1, we return 1 because the factorial of 0 or 1 is 1. - If
nis not 0 or 1, we have a recursive case. We then calculate the factorial by multiplyingnwith the factorial ofn-1. To do this, we call thefactorialfunction again with the parametern-1. - In the
mainfunction, we initialise a variablenumto 5 (the number whose factorial we want to calculate). - We call the
factorialfunction withnumas the argument and store the result in the variableresult. - Finally, we use
printfto display the result.
When the program is run, it will (hopefully) calculate the factorial of 5 using recursion and print the result as âThe factorial of 5 is 120â (if not, then we need to keep calm and debug đ).
When to use Recursion
Recursion is an excellent tool for solving problems that can be broken down into smaller and simpler sub-problems. Here are some situations in which recursion can be helpful:
- Sorting Algorithms: Some sorting algorithms such as quicksort and mergesort use recursion to divide the problem into smaller sub-problems.
- Search Algorithms: Some search algorithms such as binary search and depth-first search use recursion to explore a problem space.
- Mathematical Problems: Recursive solutions are often used in mathematical problems such as the Fibonacci sequence or calculating factorials.
When not to use Recursion
Recursion as said previously can be a powerful tool, but it is not always the best solution to a problem. Here are some situations in which recursion should not be used:
- Large Data Sets: Recursion can cause stack overflow errors if too many function calls are made. This can be a problem when dealing with large data sets.
- Deeply Nested Recursion: Deeply nested recursion can be difficult to understand and debug, leading to errors and performance issues.
- Overhead: As mentioned earlier, each function call requires additional memory, which can lead to performance issues when dealing with large data sets.
Conclusion
While recursion can be a powerful technique, itâs important to consider the problemâs characteristics, input size, language limitations, and performance requirements before deciding to use recursion or opt for an iterative approach. Itâs important to have a base case that terminates the recursion. Otherwise, the function will keep calling itself indefinitely, leading to an infinite loop (which isnât a bad thing if you love gifts…but at some point, youâll want to get to the base case sooner than later đ¤).
Thanks for reading. Happy Coding!
