Recursion to Iteration Conversion
Consider the following two methods, which are intended to return the same value for any positive integer n.
public static int mystery1(int n)
{
if (n > 1)
{
return 5 + mystery1(n - 1);
}
else
{
return 1;
}
}
public static int mystery2(int n)
{
int total = 0;
int x = 1;
while (x < n)
{
total += 5;
x++;
}
return total;
}
Which of the following changes to mystery2, if any, is required for the methods to work as intended?
A
No change is required; the methods, as currently written, return the same values when they are called with the same positive integer parameter n.
B
The variable x should be initialized to 0.
C
The variable total should be initialized to 1.
D
The condition in the while loop header should be x < n - 1.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | singhris000 | 1 | 2 | 1m 29s | 1 |
| #2 | bommasam000 | 1 | 2 | 1m 58s | -28 |
| #3 | richa.tuli | 1 | 2 | 5m 50s | -260 |
Items per page:
10
1 – 3 of 3
APFIVE