Hello,
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]<?php
for($num=1; $num <= 10; $num++)
{
echo “Number: $num
”;
}
?>[/php]
…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 a random number up to 10) which I ran into, for example:
[php]<?php
$number = rand(1,10);
$factorial = 1;
for ($counter=1;$counter <= $number; $counter++)
{
$factorial = $factorial * $counter;
}
echo “The factorial of $number is $factorial”;
?>[/php]
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]<?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”;
?>[/php]
I’m stumped trying to understand 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.
Thank you in advance.
Chris