Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Sometimes the best way to grasp an abstract concept is to translate it to a real life example (usually a stupid example). So I'll try to explain recursion to you with an <stupid> example, let's say that you want to take a shower, but you have your pijamas and your underwear on. What you must do is take all your clothes, one by one, and then get into the shower and take the bath. You first take off your pijama shirt (you have 2 pieces left), you then remove your pijama pants (1 piece left) and finally you remove your underwear. Notice that this is a repetitive pattern that must be repeated a couple of times in this case (in other case, you might have more clothe pieces, so you will do this process more). Finally when you're naked, you ask yourself: do I need to remove another piece? NO!, you reply, and you proceed to go and take the bath.

In recursion, you have 3 main components: -A function that performs the same action a repeated number of times, except for when you meet a base case (end of the recursion) -A value that must be tracked and modified in order to perform the said action n times, and know when to stop doing it -A base case that stops the repeating action, and usually performs another 1 time action.

In our example, our components are: - Function <undress to take a shower> that performs the repeated action of taking a piece of cloth off. - Value tracked, which is the <number of pieces of cloth you have left to get naked>, and on each iteration or call of the function will be reduced by 1 (asuming you're taking 1 piece at a time). - Base case, which would be <when you have no pieces of cloth left to remove = you're naked> and you can perform the last 1 time executed action which is <take the bath>.}

Notice the importance of the base case, otherwise your program will keep iterating and the program will get stucked.

Hope that this helps.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: