How To Think Recursively In Programming
To think recursively is one of the tricky parts while trying to write code. Atleast for me I was not able to grasp the recursive approach well until I was in 2nd year of my college.
But, we can train our brain to think recursively and make it a part of our day to day life. In this blog I'm going to tell what is recursion and how recursion works.
Let's get into it.
What is the recursive approach ?
The only rule of thumb to keep in mind is if we have a task which gets split on every iteration into two or more similar tasks then we can think of it as recursion i.e it is repeating itself over and over again.
Recursion Examples
Let's say we have a function which logs number from 1 to 10. Below is how we can solve this using recursion -
function printNumber(num){
if(num > 10){
return; //if number greater than 10 then exit the function
}
console.log(num); //output number to console
printNumber(num + 1); //increment value of number on each call
}
printNumber(1); //call the printNumber recursive function
As soon as we call the code above , the printNumber function will call itself again and again until the value of variable num becomes greater than 10.
The condition that stops the recursive function is called its base case . In above code line 2 is the base case where the code execution stops.
So, we can break down recursion into 3 steps -
- Create a function with a base condition upon reaching which the recursive call is stopped.
- Pass the function arguments which will trigger the base condition.
- Pass the next arguments which will trigger the recursive call only once.
In the above code example, step 1 is to create printNumber function with base case when number > 10 and step2 is when we pass a argument that triggers that base case i.e passing 11 and finally step 3 is when we call the function for numbers which are less than 10.
Conclusion
Hurray! You have just learned one of the fundamental approach of recursion in programming. Just remember whenever we have a task which degenerates into two or more similar tasks we can use recursion. Make sure we always have atleast one base case to stop recursive calls otherwise we will run out of memory and hence will cause an error.
Thanks for reading this tutorial on recursion basics !