1. 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'
|
This is only the first few lines of this paper. If you would like to view the entire paper you need to register here.
|
Get Instant Access to 100,000 Essays!!
|
|