+ 1

Need help i just don't understand why this codes output is 1 3 6 10 15 21 can anyone explain

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)

1st Sep 2022, 3:39 PM
Powfu Powfu
Powfu Powfu - avatar
1 Odpowiedź
+ 3
For Example: k = 4 tri_recursion(4) => 4 + tri_recursion(3) New call tri_recursion(3) => 3 + tri_recursion(2) New call tri_recursion(2) => 2 + tri_recursion(1) New call tri_recursion(1) => 1 + tri_recursion(0) => 1 + 0 this prints 1 , and returns 1 to privoius incomplete call. So then it's previous call is : tri_recursion(2) => 2 + tri_recursion(1) = 2 + 1 => 3 print(3) return 3 to it's previous call tri_recursion(3) => 3 + tri_recursion(2) => 3 + 3 this prints 6 , and returns 6 to it's previous and first call. tri_recursion(4) => 4 + tri_recursion(3) => 4 + 6 = 10. You have print statement after this calculation. So it print result. And also same value is returned to function call. Similar (5) => 5+4+3+2+1 = 15 printing each value. For 6: 15+6=21 For 7: 21+7=28 Hope it helps..
1st Sep 2022, 4:03 PM
Jayakrishna 🇮🇳