Hello,
This is my VERY FIRST POST. Wasn't sure if this should go on the "MATH" questions or here so I posted on both.
Total Newbie here. Currently on LOOPS.
I get how “While” and “For” (which is a compact version of While, correct?) execute a block of code for specified number of times, or while a specified condition is true.
I understand this:
<?php
for($num=1; $num <= 10; $num++)
{
echo "Number: $num<br />";
}
?>
…which repeats the count from ONE to TEN
My questions are more for understanding “the sequence by which loops process code” (I hope I’m using the right terminology).
Take these codes (for getting factorials of random number up to 10) which ran into, for example:
<?php
$number = rand(1,10);
$factorial = 1;
for ($counter=1;$counter <= $number; $counter++)
{
$factorial = $factorial * $counter;
}
echo "The factorial of $number is $factorial";
?>
I’d like to know how the code works—step by step. Perhaps an actual numeric assignment might clear it up for my confused mind. E.G.
$factorial = $factorial (1 based on the condition?) * $counter (starts at 1?);
So it repeats?—1 x 1
Then 1 ($factorial) x 2 ($counter +1)?
Then…..?
How does the formula for factorials (e.g. FIVE: 5x4x3x2x1=120) work here?
-----------------
Same Question with this (which seems to be the reverse):
<?php
$number = rand(1,10);
$counter=$number;
$factorial = 1;
for ($counter=$number;$counter >0;$counter--)
{
$factorial = $factorial * $counter;
--1 ($factorial) x random number ($counter) say, 5
--Then 1 x 5 minus 1=4
--Then 1 x 4?
}
echo "The factorial of $number is $factorial";
?>
I’m stumped trying to understand the how the code processes. Maybe I’m completely off the mark. I’d truly appreciate some enlightenment.
Pardon the long questions. I just want to learn this completely before moving forward.
I've made the php code parts bold to easier distinguish from my comments/questions.
Thank you in advance.
Fletch