Recursion to Iteration Conversion
Which, if any, of the following changes to mystery2 is required so that the two methods work as intended?
Consider the following two methods, which are intended to return the same values when they are called with the same positive integer parameter 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, if any, of the following changes to mystery2 is required so that the two methods work as intended?
A
The variable x should be initialized to 0.
B
The condition in the while loop header should be x < n - 1.
C
The variable total should be initialized to 1.
D
No change is required; the methods, as currently written, return the same values when they are called with the same positive integer parameter n.
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 |
APFIVE