0

help us to understand the logic of the following code in Python(recursive function):

def tri_recursion(k):
  if(k > 0):
    result = k + tri_recursion(k - 1)
    print(result)
  else:
    result = 0
  return result

print("\n\nRecursion Example Results")
tri_recursion(6)

Output:

Recursion Example Results
1
3
6
10
15
21

When I try to understand the logic of this program and try to predict the output I don't get the output I get only the print line output as "Recursion Example Results", but when I compile and execute it, the output comes like which I given above.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    *"I get only the print line output as "Recursion Example Results"* Why are you ignoring `print(result)`? Perhaps start with a smaller `k` value. – DeepSpace Jan 30 '22 at 10:53
  • `print(result)` will be printed for each recursion call except the last. Why do you expect something different? – sagi Jan 30 '22 at 10:54
  • Can you explain why you think it shouldn't output anything else? 6 is greater than 0, so `k > 0` will be true at least once, meaning at least one print() statement will be reached... – Mathias R. Jessen Jan 30 '22 at 10:57

0 Answers0