English subtitles

← Using Recursion - Intro to Computer Science

Get Embed Code
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.