Recursion, a bit confused

Hi,

Please help me understand this better, I’m having a hard time understanding the output from this portion of the code:

result = k+tri_recursion(k-1)

Recursion is an abstract concept, the only way I could visualize the process is by writing this:

tri_recursion(6)
                                                                                                     
6 + tri_recursion(5)                         6 + 15 = 21
	5 + tri_recursion(4)                     5 + 10 = 15                  
		4 + tri_recursion(3)                 4 + 6 = 10      
			3 + tri_recursion(2)             3 + 3 = 6         
				2 + tri_recursion(1)         2 + 1 = 3     
					1 + tri_recursion(0) <- but here k = 0, so 1 + tri_recursion(0) = 1 + 0 = 1

Also this might make it more clear.. i know, it's tough and mind boggling.

tri_recursion(1) = 1 + tri_recursion(0) = 1 + 0  = 1
tri_recursion(2) = 2 + tri_recursion(1) = 2 + 1  = 3
tri_recursion(3) = 3 + tri_recursion(2) = 3 + 3  = 6
tri_recursion(4) = 4 + tri_recursion(3) = 4 + 6  = 10
tri_recursion(5) = 5 + tri_recursion(4) = 5 + 10 = 15
tri_recursion(6) = 6 + tri_recursion(5) = 6 + 15 = 21

Important to note the value of k keeps decrementing when called recursively.
It’s easier to visualize by working your way down on the left side, and then work your way back upward on the right side.
Maybe someone can help out to explain it more clearly.

2 Likes

great I was very confused but now it is clear