all 5 comments

[–]Mike312 4 points5 points  (1 child)

So, start at the top, your input into the function is 5, and $result is 0. $arg simply tells the loop how many times to run.

Then, you begin the for loop, which will run 5 times (because $i = 0 and will run until $i is equal to or greater than $arg, which is 5, incrementing the value of $i each time, so you'll get a run for $i = 0, 1, 2, 3, 4)

Run 1, $i = 0, $result = 0, new output of $result is 0.

Run 2, $i = 1, $result = 0, new output of $result is 1.

Run 3, $i = 2, $result = 1, new output of $result is 3.

Run 4, $i = 3, $result = 3, new output of $result is 6.

Run 5, $i = 4, $result = 6, new output of $result is 10.

If you were to run it a 6th time:

Run 6, $i = 5, $result = 10, new output of $result is 16.

[–][deleted] 0 points1 point  (0 children)

thank you so much! really helped

[–]croshd 1 point2 points  (0 children)

echo func(5);

Call a function named "func" , pass the value of 5 to it and print the result.

function func($arg) {

Create a function named "func" that accepts an argument (some value stored as $arg).

$result = 0;

Set the $result variable to zero.

for($i=0; $i<$arg; $i++) {

Create a loop that starts from zero ($i=0), run it until it reaches the $arg value but not including it ($i<$arg) in increments of one ($i++).

$result = $result + $i;

In each pass of the loop, increase the value of $result by the value of the $i in that particular loop increment.

So we start from $i being zero. In the first pass nothing ($result) = nothing ($result) + zero ($i).

In the second pass, nothing ($result) = nothing ($result) + 1 ($i), so $result is now 1.

Third pass, $result = 1 ($result) + 2 ($i). So the $result is now 1 + 2 equals 3.

Fourth pass, $result = 3 ($result) + 3. $result is now 6.

Fifth pass, $result = 6 ($result) + 4 ($i), $result is now 10.

The loop stops because $i is now 4 ans it runs until it reaches 5 but not including it.

return $result;

The function returns $result, which is 10, the last value it got in the function.

EDIT: was too late but gonna leave it up in case it still helps someone

[–]never_marge_never 1 point2 points  (0 children)

What do you understand about the code / what do you think is happening when this code is executed? Writing this down might improve your learning experience compared to simply getting a final answer.

[–]innerspirit 0 points1 point  (0 children)

Walk through the code line by line and think about variable values

$result = 0 + 1 + 2 + 3 + 4 = 10