DEV Community

Dayo Jaiye
Dayo Jaiye

Posted on

What is Recursion?

In this article I will explain the term recursion to give you a clear understanding. Let's get into it! πŸ™‚

Recursion is a programming technique in which a function calls itself to solve a problem by breaking it down into smaller sub-problems. It is a powerful tool in solving problems that can be broken down into smaller, similar problems.

A good everyday example to understand recursion in programming is the process of folding a piece of paper in half multiple times.

Let's say you start with a sheet of paper and fold it in half. You now have two smaller sheets of paper, each with half the size of the original sheet.

You can repeat this process by folding each of the smaller sheets in half, which will result in four even smaller sheets of paper. If you continue folding each smaller sheet in half, you will eventually end up with many tiny sheets of paper, each with a very small size.

In programming, this process can be represented using recursion. Here is an example of a JavaScript function that uses recursion to simulate the process of folding a piece of paper in half multiple times:

function foldPaper(numFolds, paperSize) {
  if (numFolds === 0) {
    return paperSize;
  } else {
    const halfSize = paperSize / 2;
    return foldPaper(numFolds - 1, halfSize);
  }
}

console.log(foldPaper(5, 8.5)); // Output: 0.1328125
Enter fullscreen mode Exit fullscreen mode

In this example, the foldPaper function takes two arguments: numFolds and paperSize. numFolds represents the number of times the paper should be folded, and paperSize represents the initial size of the paper.

The function uses a base case (numFolds === 0) to terminate the recursion. If numFolds is 0, the function simply returns the paperSize.

If numFolds is not 0, the function calculates the size of the paper after folding it in half (halfSize) and calls itself with numFolds - 1 and halfSize as arguments. This process continues until numFolds reaches 0, at which point the function returns the final size of the paper.

So, when we call foldPaper(5, 8.5), the function calls itself with numFolds equal to 4, then 3, then 2, then 1, and finally 0. At each step, the paperSize is halved, resulting in a smaller and smaller size. The final result is 0.1328125, which represents the size of the paper after folding it 5 times.

If you find this helpful, show me❀️

Latest comments (0)