|
|
Pages: 0
0. Write a function that returns the factorial of a number. (Solution: This is a typical, can-you-program warm-up
question. Example 1 shows the iterative and recursive solutions. Notice that in both solutions, I check the
input values and boundary conditions. Factorials of negative numbers are undefined, and the factorial of
both 0 and 1 are 1. The functions in Example 1 handle these cases correctly, and they initialize all variables.
(a) int iterative_factorial (int number) { int rval = 1; /* first check input values */ if (number < 0)
{ /* we'll return -1 if there's an error */ return (-1); } for (int i = number; i > 1; i--) { rval = rval * i; }
return (rval); } (b) int recursive_factorial (int number) { if (number < 0) { /* we'll return -1 if there's an
error */ return (-1); } else if ((number == 0) || (number == 1)) { return (1); } else
{ return recursive_factorial (number-1) * number; } })
|
|
Pages: 0
NEW!!! TOOOO Many results in general search?!! Try this customized search engine for searching online books
|
Job Openings For Freshers
|