+ 1
Can anyone explain how we get 8 here, please!
What is the output of this code? function expo($b,$e){ if($e==0) return 1; $result =$b; for($i=1;$i<$e;$i++) $result *=$b; return $result; { echo expo(2,3); Answer: 8
4 Respuestas
+ 4
In the function call expo(2,3), $b is set as 2 and $e is set as 3.
The first 'if' checks if $e is equal to 0. Since it is 3, it returns False and the function continues.
$result is then set equal to $b (so $result is 2).
The 'for' loop then runs. Here $i starts off as 1, and loops while $i is less than 3. $i is incremented with each loop. So, on the first loop, $i is 1, on the second loop, $i is 2. Since $i would be 3 on the next loop, the loop stops there as it only loops when $i is LESS THAN 3. So we can see that the 'for' loop is executed twice.
The 'for' contains the statement
$result *= $b;
Now, this is the same as writing
$result = $result * $b;
So on each iteration, $result is multiplied by $b (which is 2). With 2 iterations (as discussed earlier) $result (2) is multipled by $b (2) twice. So 2 * 2 * 2 = 8.
+ 3
I modified the code and now it works.
You can't put a "return" inside a for loop, because "return" ends the process, so what happens in your code is "$result *= $b" ONCE.
Check the corrected code here ( https://pastebin.com/VSJtdWUh )
I formatted the code btw.
Glad to help
Yanko_?
+ 2
The function expo calculates exponent => 2^3 = 2*2*2 => 8.
https://code.sololearn.com/wenVsgMX0ZqK/?ref=app
+ 2
Thanks for you all