Sovi.AI - AI Math Tutor

Scan to solve math questions

QUESTION IMAGE

what happens when we call sum_to(-5) a it returns the value -15 (-5 + -…

Question

what happens when we call sum_to(-5)
a it returns the value -15 (-5 + -4 + -3 + -2 + -1 + 0).
b the program appears to do nothing (it is doing infinite recursive calls).
c the program crashes since there are too many function calls.
def sum_to(num):
if num == 0:
return num
return num + sum(num-1)

Explanation:

Brief Explanations

To determine what happens when sum_to(-5) is called, we analyze the recursive function sum_to(num):

  • The base case is when num == 0, it returns num.
  • For the recursive case, it returns num + sum(num - 1). But when num = -5, the recursive call is sum(-5 - 1) = sum(-6), then sum(-7), and so on. Since the base case (num == 0) is never reached (as num is decreasing past 0 and never becomes 0 in this path), the function will keep making recursive calls infinitely. Option A is incorrect because the sum calculation as described there would require the base case to be reached or a correct recursive path, which isn't the case here. Option C is incorrect because infinite recursion doesn't immediately crash the program in the same way as too many finite calls (it's an infinite loop of calls, not a stack overflow from too many finite calls right away, and the program "appears" to do nothing as it's stuck in recursion). So the program does infinite recursive calls.

Answer:

B. The program appears to do nothing (it is doing infinite recursive calls).