Jump to content

Understanding Loop "Process"--Factorial example


Fletch

Recommended Posts

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.