Converting Iterative Code to Recursive Code
In this lesson, we'll learn how to convert an iterative code to recursive code.
We'll cover the following
The key to transforming iterative code to recursive code is to find the specific lines of code that get transformed between the two implementations.
Steps for Converting Iterative Code to Recursive
-
Identify the main loop
- This loop should be modifying one or more variables
-
Use the loop condition as the base case and the body of the loop as the recursive case.
-
The local variables in the iterative version turn into parameters in the recursive version.
-
Compile and rerun tests.
-
Refactor the new function: You may be able to remove some temporary variables and find a better structure for the conditional statement in the recursive function.
Let’s have a look at an example:
Reverse a String
By reversing we simply mean that we can take the string and flip it. All the letters in the front, go to the back and vice versa.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.