Page 363 - computer science (868) class 11
P. 363
4 return 1;
5 if(n%2==0)
6 return 1 + check(n/2);
7 else
8 return 1 + check(n/2 + 1);
9 }
Dry run/working of the preceding program is as follows:
1 1+ check(1) check(1) popped 1+1=2
2 1+ check(2) check(2) popped 1+1+1=3
4 1+ check(4) check(4) popped 1+1+1+1 =4
7 1+ check(7) check(7) popped 1+1+1+1+1=5
13 1+ check(13) check(13) popped 1+1+1+1+1+1=6
25 check(25) check(25) popped Stack empty 6
n Method call Method popped Value returned
When n = 25 value returned = 6
2 1+ check(1) check(1) popped 1+1=2
2 1+ check(2) check(2) popped 1+1+1=3
3 1+ check(3) check(3) popped 1+1+1+1=4
5 1+ check(5) check(5) popped 1+1+1+1+1=5
10 check(10) check(10) popped Stack empty 5
n Method call Method popped Value returned
When n = 10 value returned = 5
Let us learn to write the recursive Java code for the following problem and see how it works.
n
Program 3 Define a class Power which calculates a . The class description is as follows:
Class name : Power
Data Members
int a, n : To store number and power respectively
Member Methods
void input(int a1, int n1) : Initialises a as a1 and n as n1
int calpower(int aa, int nn) : Using recursive technique, returns aa and nn
n
void print() : Calls calpower(int, int) to calculate a . ‘n’ can be both
positive and negative
static void main() : Creates object and calls the other methods to perform the
above operation
1 class Power
2 { int a, n;
3 void input(int a1, int n1) // accepts number as parameter
4 { a = a1;
361
Recursion 361

