Page 405 - Computer science 868 Class 12
P. 405
14 return 1;
15 else
16 return n*fact(n-1); // recursive case
17 }
18
19 void print()
20 {
21 int r = fact(a);
22 System.out.println(a+"! = "+r);
23 }
24
25 public static void main()
26 {
27 Factorial ob = new Factorial();
28 ob.accept();
29 ob.print();
30 }
31 }
The output of the preceding program is as follows:
Enter a number
5
5! = 120
The dry run of the above program is shown below with n = 5:
return 1 1 x
st
0 0 = 0 true 1 x fact(0) 1 fact(0) popped 1 × 1 = 1
base case
nd
1 1 = 0 false 2 x fact(1) 2 fact(1) popped 1 × 2 = 2
2 2 = 0 false 3 x fact(2) 3 fact(2) 2 × 3 = 6
rd
3 3 = 0 false 4 x fact(3) 4 fact(3) 6 × 4 = 24
th
th
4 4 = 0 false 5 x fact(4) 5 fact(4) 24 × 5 = 120
th
5 5 = 0 false fact(5) 6 fact(5) 120
n n = 0 Method pushed Popped Value returned
403
Recursion 403

