Page 365 - computer science (868) class 11
P. 365

The dry run of the above program is shown with a=2 and n=5 using stack concept.

                                                                      return 1             1
                                          0      Is 0 = 0 true   2 x calpower(0)    1 × 2 = 2
                                                 base case
                                          1      Is 1 = 0 false  2 x calpower(1)    2 × 2 = 4
                                          2      Is 2 = 0 false  2 x calpower(2)    4 × 2 = 8
                                          3      Is 3 = 0 false  2 x calpower(3)    8 × 2 = 16
                                          4      Is 4 = 0 false  2 x calpower(4)    16 × 2 = 32
                                          5      Is 5 = 0 false  calpower(5)        Value returned 32
                                          n      Is n = 0        Stack              Output



                  Program 4      Define a class Factorial which calculates the factorial of a number. The factorial of a number
                                 is the product of all natural numbers from 1 to itself.  The class description is as follows:
                                 Class name                :  Factorial
                                 Data Members
                                 int a                     :  To store any number in variable a
                                 Member Methods
                                 void accept()             :  Accepts number
                                 int fact(int n)           :   Using recursive technique, calculates and returns the factorial
                                                              of n which is 1×2×3×4.....×n
                                 void print()              :  Calls fact(int) and prints the output
                                 static void main()        :   Creates object and calls the other methods to perform the
                                                              above operation

                   1      import java.util.*;

                   2      class Factorial
                   3      {

                   4          int a;
                   5          void accept()

                   6          { // inputting
                   7              Scanner sc = new Scanner(System.in);

                   8              System.out.println("Enter a number");
                   9              a = sc.nextInt();

                  10          }
                  11          int fact(int n)

                  12          {
                  13              if(n == 0)   // base case









                                                                                                                       363
                                                                                                           Recursion   363
   360   361   362   363   364   365   366   367   368   369   370