Main Menu

Deitel Exersices
Downloads
Contact ME


 


Back


Links
CE Main Site
Sharif University
Wikipedia
2Del
PHP
Javascript





    

In the name of GOD


Deitel Exercise : 3.44

(Visualizing Recursion) It is interesting to watch recursion in action. Modify the Factorial function of fig.3.14 to print its local variable and recursive call parameter. For each recursive call display the outputs on a seperate line and add a level of indentation. Do your utmost to make the output clear, interesting and meaningful. Your goal here is to design and implement an output format that helps a person undestands recursion better. You may want to add such display capabilities to the many other recursion examples and exercises throughout the text.


11
12     unsigned long factorial( unsigned long ); //function prototype
13
14     int main()
15     {
16          // Loop 10 times. During each iteration, calculate
17          // factorial i and display result.
18          for ( int i = 0 ; i <= 10 ; i++ )
19               cout << setw( 2 ) << i << "! = "
20                    << factorial( i ) << endl;
21
22          return 0;     // indicates successful termination
23
24     }      // end main
25
26     // recursive definition of function factorial
27     unsigned long factorial( unsigned long number )
28     {
29          // base case
30          if (number <= 1 )
31               return 1;
32
33          // recursive step
34     else
35               return number * factorial( number - 1 );
36
37         // end function factorial


  0! = 1
  1! = 1
  2! = 2
  3! = 6
  4! = 24
  5! = 120
  6! = 720
  7! = 5040
  8! = 40320
  9! = 362880
10! = 3628800


     Fig. 3.14 Factorial calculation with a recursive function. (Part 2 of 2.)