Java programming, I need it assap please! Thumbs up waiting for speed and accura
ID: 3814437 • Letter: J
Question
Java programming, I need it assap please! Thumbs up waiting for speed and accuracy, thank you very much!
Given that the following method definition belongs to a class.
int evaluate(int x)
{
if (x == 1)
return 1;
else
return x + evaluate(x-1) ;
}
What is displayed when the following statement is called?
System.out.println("The result is " + evaluate( 5) );
Select one:
a. 15
b. The code will not compile because the keyword, if, wants the associated keyword, else.
c. 5 4 3 2 1 0
d. 21
e. 5 4 3 2 1
int evaluate(int x)
{
if (x == 1)
return 1;
else
return x + evaluate(x-1) ;
}
Explanation / Answer
int evaluate(int x)
{
// base case when x is 1, return 1
if (x == 1)
{
return 1;
}
// recursively call function
// adding x to result and decrementing x
else
{
return x + evaluate(x-1) ;
}
}
/*
evaluate(8) will result in
recursive call: 5+evaluate(4)
recursive call: 4+evaluate(3)
recursive call: 3+evaluate(2)
recursive call: 2+evaluate(1)
Base case called: return 1
The result is 15
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.