Functions and recursion: Difference between revisions

Line 193: Line 193:
:::*<tt>factorial(1)<tt> returns 1 so <tt>factorial(2)<tt> can return 2&times;1...2
:::*<tt>factorial(1)<tt> returns 1 so <tt>factorial(2)<tt> can return 2&times;1...2
::*<tt>factorial(2)<tt> returns 2 so <tt>factorial(3)<tt> can return 3&times;2...6
::*<tt>factorial(2)<tt> returns 2 so <tt>factorial(3)<tt> can return 3&times;2...6
:*<tt>factorial(3)<tt> returns 6 so <tt>factorial(4)<tt> can return 4&times;3...24
:*<tt>factorial(3)<tt> returns 6 so <tt>factorial(4)<tt> can return 4&times;6...24


Many times, a recursive solution to a problem is very easy to program. The drawback of using recursion is that there is a lot of overhead. Every time a function is called, it is placed in memory. Since you don't exit the <tt>factorial<tt> function until n reaches 1, n functions will reside in memory. This isn't a problem for the simple factorial(4), but other functions can lead to serious memory requirements.
Many times, a recursive solution to a problem is very easy to program. The drawback of using recursion is that there is a lot of overhead. Every time a function is called, it is placed in memory. Since you don't exit the <tt>factorial<tt> function until n reaches 1, n functions will reside in memory. This isn't a problem for the simple factorial(4), but other functions can lead to serious memory requirements.