Page 392 - Cs_withBlue_J_C11_Flipbook
P. 392
14 return 1;
15 else
16 return n*fact(n-1); // recursive case
17 }
18 void print()
19 {
20 int r = fact(a);
21 System.out.println(a+"! = "+r);
22 }
23 public static void main()
24 {
25 Factorial ob = new Factorial();
26 ob.accept();
27 ob.print();
28 }
29 }
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 × fact(0) 1 fact(0) popped 1 × 1 = 1
base case
1 1 = 0 false 2 × fact(1) 2 fact(1) popped 1 × 2 = 2
nd
2 2 = 0 false 3 × fact(2) 3 fact(2) 2 × 3 = 6
rd
th
3 3 = 0 false 4 × fact(3) 4 fact(3) 6 × 4 = 24
th
4 4 = 0 false 5 × fact(4) 5 fact(4) 24 × 5 = 120
5 5 = 0 false fact(5) 6 fact(5) 120
th
n n = 0 Method pushed Popped Value returned
390390 Touchpad Computer Science-XI

