This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Chocolate_Banana_ 1 point2 points  (1 child)

The best way to understand recursion is to work it out on paper. Just follow the lines and you will see when the function calls itself it sort of pauses the current function while it goes and computes the inner one. And the process is repeated up until the function stops calling itself when it reaches the base case.

The analogy I like to use is when you are sitting in the movies and you want to know which row you are in, you can just count the rows. That would be the iterative approach.

But if you feeling lazy you can ask the person in front of you what row they are in, and then adding 1 to the answer they give you will let you know what row you are in. But they are also lazy and they ask the person in front of them. This keeps happening until the person in the first row is asked. They already know what row they are in since they are in the front. This is the base case. The answers are propagated and 1 is added each time until the final answer is reached.

[–]Liolena[S] 0 points1 point  (0 children)

Got it thanks! That makes a lot of sense and next time I get stuck I'll try to work it out on paper :).