Given the triangle number sequence: 1, 3, 6, 10, 15, 21, 28, 36, 45, … The recur
ID: 3842932 • Letter: G
Question
Given the triangle number sequence:
1, 3, 6, 10, 15, 21, 28, 36, 45, …
The recursive triangle function below calculates the triangle number at term n where n is assumed to be greater than 0 (i.e. n starts at 1). However, there is something wrong with the recursive triangle Java function below. For example, if you call the function “triangle(3);”, you would expect it to return 6 (because it is the 3rd term in the sequence), but this function doesn’t.
After reviewing the code, answer the following questions
If the current incorrect function was called as “int result = triangle(4);”, what would the value be in result?
What code change(s) would you make to fix the triangle function?
// Assume term > 0
public int triangle(int term)
{
if (term == 1)
return term;
return term * triangle(term – 1);
}
Explanation / Answer
Its plus not multiply...
Here is code:
public static int triangle(int term) {
if (term == 1) {
return term;
}
return term + triangle(term - 1);
}
The sequence is represent as follows:
so we need to use +
1 3 6 10 15 1 1 + 2 1 + 2 + 3 1 + 2 + 3 + 4 1 + 2 + 3 + 4 + 5Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.