144,100 views
37 votes
37 votes
What is wrong with the following recursive sum method? The method is supposed to sum up the values between 1 and x (for instance, sum(5) should be 5 + 4 + 3 + 2 + 1 = 15). public int sum(int x) { if (x == 0) return 0; else return sum(x – 1) + x; } Group of answer choices the base case should return 1 instead of 0 the recursive case should return sum(x – 1) + 1; instead of sum(x – 1) + x; the recursive case should return sum(x) + 1; the method should return a boolean instead of an int the base case condition should be (x <= 0) instead of (x = = 0)

User David Yang
by
2.4k points

1 Answer

24 votes
24 votes

Answer:

The base case condition should be (x <= 0) instead of (x = = 0)

Step-by-step explanation:

The given recursive function works fine for positive number. However, it returns an error when the value passed to the function is negative.

To prevent this, the base case should be x <= 0.

This will allow the program returns 0 if a negative number or 0 is passed to the function.

Hence, the changes to be made is to replace the base case with x <= 0

User Shawntel
by
2.8k points