Archie Court Archie Court - 1 year ago 56
PHP Question

How do I square a number using a for loop in php?

My task, using php, is to create a random number, then make that number multiply itself. However i cannot use the multiply operator (*) and have been told to create a for loop instead however I'm having some troubles.

$startNum = rand(1,10);

for ($i = $startNum; $i <= 10; $i++)
echo $i;

This is what i have so far, however this is completely wrong and will only get a random number and count to 10 from it.
Any help would be very appreciated, thanks.

Answer Source

When squaring you are just multiplying a number by itself, another way to do this is through addition, add a number to itself x amount of times. So, with 4 squared, that is 4 * 4 or, 4 + 4 + 4 + 4.

Doing this in a for loop should be as simple as

$startNum = rand(1,10);
$endNum = 0;    

for ($i = 0; $i < $startNum; $i++)
  $endNum += $startNum;
echo $endNum;

Caveat: I don't program Php so forgive syntax errors.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download