Fletch Posted January 17, 2012 Share Posted January 17, 2012 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 Quote Link to comment https://forums.phpfreaks.com/topic/255190-understanding-loop-process-factorial-example/ Share on other sites More sharing options...
Fletch Posted January 17, 2012 Author Share Posted January 17, 2012 Additional question: When does the Random number come in during the processing of the code? Is it determined first or later in the sequence? Fletch Quote Link to comment https://forums.phpfreaks.com/topic/255190-understanding-loop-process-factorial-example/#findComment-1308404 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.