Prev | Current Page 153 | Next

Carl Reynolds and Paul Tymann

"Schaum's Outline of Principles of Computer Science"

The factorial function calls itself repeatedly until the number passed
in is 1, at which point it returns the value 1 to the last caller, which can then return to its caller, etc.
Some would say that the recursive function is more self-descriptive. It??™s certainly shorter, and simpler to write.
CHAP. 4] SOFTWARE 57
To write a recursive function, one first defines the ???grounding condition,??? or ???base case,??? at which the
recursion terminates. In the example of factorial, both 1! and 0! return 1 by definition, and no further
computation is necessary. When the grounding condition occurs, the function should stop calling itself and
simply return the value 1.
The factorial for a larger number can be defined as the larger number times the factorial of the next smaller
integer. So the factorial function can be thought of as a process: multiply the number times the factorial of
the next smaller number. The process continues until the number being evaluated is 1. At that point, the function
returns 1, which provides the factor for computing 2!, which answer provides the factor for computing 3!, which
answer provides the factor for computing 4!, etc. The recursion ???unwinds??? providing the answer for the factorial
of the larger number.


Pages:
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
dobry katalog Opoczno tanie pokoje miedzyzdroje jarosławiec chemia kosmetyki