Recursion... can be simple.

Recursion... can be simple.

Hey guys,

Let’s talk about recursion.

Imagine you have a big task, and to solve it, you need to do a smaller version of the same task. Recursion is like telling a friend to do part of the job, and if that part also needs the same kind of help, they'll ask another friend, and so on.

Things to note: Recursion consists of two things, a base case and a recursive case.

Base case: a base case is like a safety net or a stopping point in a recursive function. It's a condition that, when met, tells the function to stop calling itself and return a result immediately.

Recursive case: The recursive case is the part of a recursive function where the function calls itself to solve a smaller instance of the same problem. In other words, it's like breaking down a big task into a smaller, more manageable task of the same type.

Let's look at a simple example in TypeScript - calculating the factorial of a number.

// Function to calculate factorial using recursion

function factorial(n: number): number {

// Base case: If the number is 0 or 1, the factorial is 1

if (n <= 1) {

return 1;

} else {

// Recursive case: n! = n * (n-1)!

return n * factorial(n - 1);

}

}

// Example usage

const num = 5;

const result = factorial(num);

// Print the result

console.log(`Factorial of ${num} is: ${result}`);

In simpler terms:

  1. Base Case: If the number is 0 or 1, the answer is 1. It's like saying, "If your task is super tiny, just do it and don't ask anyone else."
  2. Recursive Case: If the number is more than 1, then break the task into a smaller part and ask someone (in this case, ask yourself with a smaller number).

Now, let's imagine you want to know the factorial of 5.

  1. You ask, "Hey, what's the factorial of 5?"
  2. You realize, "Hmm, to find that, I need to know the factorial of 4."
  3. So, you ask again, "Hey, what's the factorial of 4?"
  4. Repeat until you get to the simplest task, which is the factorial of 1 (which is 1).
  5. Now, you can answer all the previous questions, and you get the final result.

Recursion is like breaking down a big problem into smaller pieces and solving each piece step by step, with each step asking the same question but with a smaller problem until you get to the simplest form.

Please subscribe to my newsletter if you like this kind of stuff! --> https://thenewdevs.substack.com/

要查看或添加评论,请登录

Ricardo M.的更多文章

社区洞察

其他会员也浏览了