Let’s say you have 7 identical robots, a table, a piece of paper, and seven markers. You ask them to draw a rainbow.
ITERATIVE
Robot 1 picks up a red marker, puts the paper on the table and draws an arc. They put the pen down and they leave.
Robot 2 picks up an orange marker, puts the paper on the table and draws another arc. They put the pen down and they leave.
Repeat for all 7 robots until the rainbow is finished.
RECURSIVE
Robot 1 picks up the red marker, hands the paper to Robot 2 and waits.
Robot 2 takes the paper, picks up the orange pen, hands the paper to Robot 3, and waits.
The process repeats until you get to Robot 7.
Robot 7 recieves the paper from Robot 6, picks up the violet pen, draws an arc, then hands the paper back to robot 6.
Robot 6 gets the paper back from Robot 7, uses the indigo pen they are already holding, draws an arc, then hands the paper back to Robot 5.
The process repeats until Robot 2 hands the paper back to Robot 1, who draws a red arc, and finishes the rainbow.
In both cases the end result is the same, the difference is how you got there.
So why use recursion instead of iteration? Because some algorithms are easier to write in code as recursive than iterative. And vice versa. Recursive algorithms take advantage of how computers operate, by placing function calls and their results on a stack, while iterative algorithms require the programmer to manage more directly how each step repeats.
At the end of the day there is no functional difference, you can replace any recursive function with an iterative one, though it’s not always easy to do so.
Latest Answers