+ 1

Can anyone explain to me how this Php code equates to 3?

Just had this question for a php challenge, and I can’t figure out how you get 3 from It. I understand one of the numbers you’ll get back from the function Is 5, but I don’t get how 3 Is the answer unless somehow sum returns a result of 15 to then be divided by 3. //code start function sum($from, $number) { $result = 0; for($i = $from; $i <= $number; i++) { $result = $result + $i; } return $result; } echo sum(0, 5) / 5; //code end Any help is appreciated, thanks.

10th Sep 2019, 6:44 PM
Jacob Sloan
Jacob Sloan - avatar
2 Answers
+ 2
Sum() return 15. For loop go over i=0,i=1,i=2,i=3,i=4,i=5 And result is the sum of all the i Result=0+1+2+3+4+5=15 Then 15/5=3 And the output is 3
10th Sep 2019, 7:03 PM
KfirWe
KfirWe - avatar
0
Yes, the output of the function is 15, so you echo 15 / 5 = 3 Now let me explain why it does return 15: Inputs / variables: $from = 0 (input) $number = 5 (input) $result = 0 Now the loop: for($i = from; $i <= $number; $i++) Enter the vars and you get for($i = 0; $i <= 5; i++) Now I'm going to explain loops just to be sure: This will loop 6 times because: 1st time: $i = 0. Is $i <= 5? No: loop and i++ (=1) 2nd time: $i = 1, ... <= 5? No: loop and i++ (=2) 6th time: $i = 5, ... <= 5? No (= 5): now loop and make $i 6, so a 7th time (6 <= 5 is false) won't happen Now what it does in the loop: $result = $result + $i or $result += $i (different way of writing the same) So it will go like this: 1st: $result (=0) += $i (=0) --> 0 + 0 = 0 2nd: $result (=0) += $i (=1) --> 0 + 1 = 1 3th: $result (=1) += $i (=2) --> 1 + 2 = 3 4th: $result (=3) += $i (=3) --> 3 + 3 = 6 5th: $result (=6) += $i (=4) --> 6 + 4 = 10 6th: $result (=10) += $i (=5) --> 10 + 5 = 15 Return this number, which is 15
10th Sep 2019, 7:16 PM
Roel
Roel - avatar