Consider the following iterative algorithm. Which recursive algorithm does the s
ID: 3779132 • Letter: C
Question
Consider the following iterative algorithm. Which recursive algorithm does the same thing as the iterative algorithm? Assume that the variable x is greater than zero. Select all that apply.
public static void int doSomething(int x) {
int result = 1;
while(x > 1) {
result = result * x;
x--;
}
return result;
}
A) public static void int doSomething(int x) {
if(x > 1)
x = x-1;
if(x == 1)
return 1;
return x * doSomething(x);
}
B) public static void int doSomething(int x) {
if(x < 2)
return x;
if(x >= 0)
return doSomething(x-1) * x;
}
C) public static void int doSomething(int x) {
if(x == 1)
return 1;
return x * doSomething(x-1);
}
D) public static void int doSomething(int x) {
if(x > 1)
return doSomething(x-1) * x;
return 1;
}
There may be multiple correct answers.
Explanation / Answer
Answer: C and D
C) public static void int doSomething(int x) {
if(x == 1)
return 1;
return x * doSomething(x-1);
}
D) public static void int doSomething(int x) {
if(x > 1)
return doSomething(x-1) * x;
return 1;
}
both are same like iterative method.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.