0
Pls I need the solution to this Question: php >> functions >> module 6 >> Q1, with comprehensive explanation pls. Thanks
3 Réponses
+ 4
@Ahmed Al/malaji:
and the comprehensive explanation? :P
function func($arg) {
$result=0;
for ($i=0; $i<$arg; $i++) {
$result=$result+$i;
}
return $result;
}
echo func(5);
The last line call the function "func", which is declared in previous lines, passing to it the value 5 as argument.
So, starting 'func', the variable $arg is initialized with the value 5.
First line of 'func', a variable named 'result' is initialized with the value of 0.
Second line, is a 'for' loop statement: in the parenthesis, you have three zones, semi-colon separated, defining respectivly:
- loop initialization ( executed once, at start of loop ): initialize the variable named 'i' to value 0;
- test condition: before each iteration ( one execution of the code block associated/nexted with the 'for' statement );
- incrementation : executing at end of each loop iterations... in this code, the varaible 'i' is incrementique ( adding one to it )...
So:
- before 1st iteration: $arg==5, $result==0, $i=0;
- test $i<$arg <=> 0<5 is true,
- so loop code block run and at end: $arg==5, $result==0 (0=0+0), $i=1; which is state before 2nd iteration...
- before 2nd iteration: test $i<$arg <=> 1<5 is true,
- so loop code block run and at end: $arg==5, $result==1 (1=0+1), $i=2;
- before 3rd iteration: test $i<$arg <=> 2<5 is true,
- so loop code block run and at end: $arg==5, $result==3 (3=1+2), $i=3;
- before 4th iteration: test $i<$arg <=> 3<5 is true,
- so loop code block run and at end: $arg==5, $result==6 (6=3+3), $i=4;
- before 5th iteration: test $i<$arg <=> 4<5 is true,
- so loop code block run and at end: $arg==5, $result==10 (6=6+4), $i=5;
- before 6th iteration: test $i<$arg <=> 5<5 is false,
- so loop code block no more running, and next instruction after the loop code block is executed, so, in this code, the value of variable 'result' ( 10 ) will be returned to the echo statement...
+ 2
Thanks man
0
10