Help With JAVA Work Sheet (Recursion)
WORKSHEET A9.1
Recursion Review
Find the output to the following code segments. Use the recursive boxes shown in Figure 9.1 of
the Lesson to help you obtain the final result. YOU MUST SHOW WORK
1. int result = identity(10);
System.out.println("The final answer is " + result);
public int identity(int num){
if(num < 1){
return 10;
}else{
return num + identity(num - 2);
}
}
2. int result2 = negative(-3);
System.out.println("The final answer is " + result2);
public int negative(int num){
if(num >= 20){
return -5;
}else{
return negative(num + 4) + 2 * num;
}
}
3. int result3 = product(1);
System.out.println("The final answer is " + result3);
public int product(int num){
if(num > 20){
return -1;
}else{
return num * product(-2 * num);
}
}
4. int mist(int n){
if ( n == 1){
return 3;
}else{
return 3 * mist(n-1);
}
}
What value does mist(5) return?
5. void misty(int n){
if(n > 4){
misty(n%4);
}
System.out.print(n/4 + “ “);
}
What sequence of numbers will the call to misty(38) yield?
6. int mistier(int n){
if ( n == 0){
return 1;
}else{
return 4 * mistier(n-1) + 2;
}
}
What value does mistier(3) return?
7. int mistiest(int n){
if ( n == 6){
return 6;
}else{
return 2 * mistiest(n+1);
}
}
What value does mistiest(2) return?
8. int whoKnows(int n){
if ( n <= 1){
return n;
}else{
return n + whoKnows(n-1);
}
}
What value does whoKnows(5) return?
9. int weird(int p, int q){
if ( p == 1){
return p +1;
}else if(q == 0){
return weird(p-1, q);
} else{
return weird(p-1, weird(p, q-1));
}
}
What does weird(2,2) return?
10. int weirder(int r, int s){
if ( r == 0 || r == s){
return 1;
}else{
return weirder(r-1, s) + weirder(r-1, s-1);
}
}
What is the return value of weirder(3,2)?
11. void weirdest(int x){
if ( x > 1){
weirdest(x/2);
}else{
System.out.print(x + " ");
}
}
What is the output of the call weirdest(40)?
11. void weirdo(int x){
if( x > 1 ){
weirdo(x/2);
}
System.out.print(x + “ “);
}
What is the output of the call weirdo(40)?
12. void weirdom(int x){
System.out.print(x + “ “);
if( x > 1 ){
weirdom(x/2);
}
}
What is the output of the call weirdom(40)?
|