→ Recursion is a process of calling itself. A function that calls itself is called a recursive function.
→ Suppose that you have a function called 'recurse()`. The recurse() is a recursive function if it calls itself inside its body
Example:
→ A recursive function always has a condition to stop calling itself.
→ Otherwise, it will call itself indefinitely.
→ Once the condition is met, the function stops calling itself. This is called a base condition.
→ So a recursive function looks like this:
→ To prevent infinite recursion, we can use if...else statement where one branch makes the recursive call, and the other doesn't. As shown in above example.
Using recursive functions (Example):
→ Suppose that you need to develop a function that counts down from a specified number to 1.
→ For example, to count down from 5 to 1:
→ In the above program, the user passes a number as an argument when calling a function.
→ In each iteration, the number value is decreased by 1 and the function countDown() is called until the number is positive.
→ Here, newNumber > 0 is the base condition.
→ When the number reaches 0, the base condition is met, and the function is not called anymore.
That's all for now.
I hope you found this thread helpful.
→ Please consider 💛 liking this tweet.
→ 🔁 Retweeting the first tweet so others can see it.