Page 170 - DCAP407_DATA_STRUCTURE
P. 170

Unit 9:  Recursion



               By definition, 1 is the value for 0!. Let us compute the factorial of 5. Figure 9.2 depicts the factorial of 5.

                                                 Figure 9.2: Factorial of 5




















               But computations will be done in reverse order as depicted in figure 9.3.

                                       Figure 9.3: Computations for Factorial of 5 in
                                                  Reverse Order






                                                                      0! = 1
                                                               1! = 1 * 0! = 1 * 1 =1
                                                           2! = 2 * 1! = 2 * 1 = 2
                                                     3! = 3 * 2! = 3 * 2 =6

                                                4! = 4 * 3! = 4 * 6 = 24
                                         5! = 5 * 4! = 5 * 24 = 120






                                Program that computes the factorial of a number using recursion.

                                #include<stdio.h>
                                /* fact is a recursive function which takes an integer variable num and returns
                                an integer value */
                                int fact (int num)
                                {
                                    /* Check if num value is equal to zero */
                                    if (num==0)
                                      /* Return the  value 1 */
                                          return 1;
                                    /* Otherwise */
                                    else
                                     /* Return num * fact (num-1) value */
                                     return (num * fact (num-1));
                                 }
                                /* Main function */




                                        LOVELY PROFESSIONAL UNIVERSITY                          163
   165   166   167   168   169   170   171   172   173   174   175