## ← Using Recursion - Intro to Computer Science

• 3 Followers
• 22 Lines

### Get Embed Code x Embed video Use the following code to embed this video. See our usage guide for more details on embedding. Paste this in your document somewhere (closest to the closing body tag is preferable): ```<script type="text/javascript" src='https://amara.org/embedder-iframe'></script> ``` Paste this inside your HTML body, where you want to include the widget: ```<div class="amara-embed" data-url="http://www.youtube.com/watch?v=VWyHjEh0tfA" data-team="udacity"></div> ``` 4 Languages

Showing Revision 7 created 05/25/2016 by Udacity Robot.

1. Ã¯Â»Â¿Student W.Q. Feng asked when do you use a recursive definition versus a 'while' loop?
2. So this is a good question and in terms of being able to solve a problem,
3. anything you can do with recursion you can also do with a 'while' loop.
4. Anything you can do with a 'while' loop you could also do with recursion.
5. So any problem you can solve either way.
6. Usually solving it with a 'while' loop would be more efficient
7. because you donÃ¢ÂÂt have the overhead of all the extra procedure calls.
8. Often solving it with recursion is a simpler and more elegant solution.
9. So depending on whatÃ¢ÂÂs more important, oftentimes the tradeoff
10. is much better where the simpler elegant solution
11. that performance difference you probably couldnÃ¢ÂÂt even measure
12. unless you were timing really carefully for really large inputs,
13. you wouldnÃ¢ÂÂt notice the difference.
14. So itÃ¢ÂÂs more important to get the solution correct and have it
15. in code thatÃ¢ÂÂs easier for you to write and easier for other people to understand,
16. in many problems the recursive solution
17. really lends itself to that. ItÃ¢ÂÂs much shorter than the iterative solution would be
18. and itÃ¢ÂÂs easier to understand and follow.
19. In places where performance matters and we saw this with the Fibonacci example
20. that if you end up blowing up the number of calls in a way
21. that makes it too slow to do recursively,
22. you might prefer a more complicated solution that involves a 'while' loop and avoids the recursive calls.