Programming in C

(Barry) #1
Recursive Functions 161

With the value of nequal to 2, the factorialfunction executes the statement

result = n * factorial (n - 1);


which is evaluated as


result = 2 * factorial (1);


Once again, the multiplication of 2 by the factorial of 1 is left pending while the
factorialfunction is called to calculate the factorial of 1.
With the value of nequal to 1 , the factorialfunction once again executes the state-
ment


result = n * factorial (n - 1);


which is evaluated as


result = 1 * factorial (0);


When the factorialfunction is called to calculate the factorial of 0, the function sets
the value of resultto 1 and returns, thus initiating the evaluation of all of the pending
expressions. So the value of factorial (0), or 1, is returned to the calling function
(which happens to be the factorialfunction), multiplied by 1, and assigned to result.
This value of 1 , which represents the value of factorial (1), is then returned back to
the calling function (once again the factorialfunction) where it is multiplied by 2,
stored into result, and returned as the value of factorial (2). Finally, the returned
value of 2 is multiplied by 3, thus completing the pending calculation of factorial
(3).The resulting value of 6 is returned as the final result of the call to the factorial
function, to be displayed by the printffunction.
In summary, the sequence of operations that is performed in the evaluation of
factorial (3)can be conceptualized as follows:


factorial (3) = 3 factorial (2)
= 3
2 factorial (1)
= 3
2 1 factorial (0)
= 3 2 1 * 1
= 6


It might be a good idea for you to trace through the operation of the factorialfunc-
tion with a pencil and paper. Assume that the function is initially called to calculate the
factorial of 4. List the values of nand resultat each call to the factorialfunction.
This discussion concludes this chapter on functions and variables.The program func-
tion is a powerful tool in the C programming language. Enough cannot be said about
the critical importance of structuring a program in terms of small, well-defined func-
tions. Functions are used heavily throughout the remainder of this book. At this point,
you should review any topics covered in this chapter that still seem unclear.Working
through the following exercises will also help reinforce the topics that have been dis-
cussed.

Free download pdf