+ 1

Help!!!

I got this question in the learn php module: function func($arg) { $result = 0; for($i=0; $i<$arg; $i++) { $result = $result + $i; } return $result; } echo func(5); what is the result of the function? can anyone give me a good explanation of how the answer is 10 im quite confused

13th Mar 2017, 10:21 AM
Karabo “Breeze” Maimane
Karabo “Breeze” Maimane - avatar
4 Respostas
+ 4
here , u passed 5 in func, hence arg=5. Now lets see the loop, for($i=0;$i<5;$i++) Here i will have values 0,1,2,3,4. Then you add result = result + i; this means result = 0 + 0; //for first iteration i=0 then for the following iterations , result = 0+1;here result is 0(0+0) and i is 1 result = 1+2; here result is 1(0+1)and i is 2 result = 3+3;here result is 3 (1+2)and i is 3 result = 6+4 ;here result is 6(3+3)and i is 4 which is 10.
13th Mar 2017, 10:29 AM
Meharban Singh
Meharban Singh - avatar
+ 3
thank you man it just became a whole lot clearer
13th Mar 2017, 10:32 AM
Karabo “Breeze” Maimane
Karabo “Breeze” Maimane - avatar
+ 1
Anytime bro
13th Mar 2017, 10:47 AM
Meharban Singh
Meharban Singh - avatar
0
thanks ...took a while but grabbed it!
31st Oct 2017, 10:39 AM
Elias Derby
Elias Derby - avatar