+ 1

Question about php

Function math($t) { If ($t == 0) return 0; return $t + math($t - 1); } echo math(6); Can somebody explain me how i get result 21 here, i'm new to php and i try to understand this. function expo($b, $e) { if ($e == 0) return 1; $result = $b; for ($i = 1; $i < $e; $i++) $result; } echo expo(2,3); Also in this one, result is 8 and i don't understand why is 8. Thank you in advance.

6th Sep 2019, 4:38 PM
Jovan Trkulja
Jovan Trkulja - avatar
2 Answers
+ 3
On first iteration the function math(6) has 6 as argument and this maths function will execute till 0 as at argument 0 it is return 0. Now look over that 1) return 6+ math(6-1) 2) return 6+5+math(5-1) 3) return 6+5+4+ math(4-1) 4) return 6+5+4+3+math(3-1) 5) return 6+5+4+3+2+math(2-1) 6) return 6+5+4+3+2+1+ math(1-1) 7) return 6+5+4+3+2+1+0 As math(0) return 0 now sum all return value 6+5+4+3+2+1+0=21 So output is 21
6th Sep 2019, 4:48 PM
Preity
Preity - avatar
+ 1
Now I understand it, thank you so much man!! Preity
7th Sep 2019, 10:29 AM
Jovan Trkulja
Jovan Trkulja - avatar