Page 404 - Computer science 868 Class 12
P. 404
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) Popping last call 1 x 2 = 2
base case
1 Is 1 = 0 false 2 x calpower(1) Popping next call 2 x 2 = 4
2 Is 2 = 0 false 2 x calpower(2) Popping next call 4 x 2 = 8
3 Is 3 = 0 false 2 x calpower(3) Popping next call 8 x 2 = 16
4 Is 4 = 0 false 2 x calpower(4) Popping next call 16 x 2 = 32
5 Is 5 = 0 false calpower(5) Stack empty Value returned 32
n Is n = 0 Stack Value popped Output
Program 2 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×2x3×4.....xn
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
402402 Touchpad Computer Science-XII

