Page 1 of 1

function problem

Posted: Wed Jan 26, 2005 9:37 am
by theweirdone
ok... so i have this code

Code: Select all

<?php

$number = 5;
echo "the number is ".$number;
echo "<br>";
square($number);
echo "the number squared is ".$number;


function square($number)
&#123;
	  $counter = $number;
	  $onumber = $number;
	  	do
		&#123;
		$number= $onumber*$onumber;
		$counter--;
		&#125; while ($counter >=1);
return $number;
&#125;
?>
and the reply is
the number is 5the number squared is 5
... the function doesn't seem to work and i'm not sure why... it's probly a very stupid mistake that i've made... would appreciate the help though... thanx...

Posted: Wed Jan 26, 2005 9:53 am
by Wayne

Code: Select all

<?php 

$number = 5; 
echo "the number is ".$number; 
echo "<br>"; 
$numberSquared = square($number); 
echo "the number squared is ".$numberSquared; 


function square($number) 
&#123; 
     $counter = $number; 
     $onumber = $number; 
        do 
      &#123; 
      $number= $onumber*$onumber; 
      $counter--; 
      &#125; while ($counter >=1); 
return $number; 
&#125; 
?>
silly question but why do you have

Code: Select all

$number= $onumber*$onumber; 
      $counter--;
in a loop, the square has already been worked out, you are just going to repeat the calculation as many times as the size of the number, which is a waste, image running the same calculation 1000 times!

Posted: Thu Jan 27, 2005 1:34 am
by theweirdone
thats a good point... thanx... so thats one of my stupid mistakes... my function still doesn't work though...

Posted: Thu Jan 27, 2005 1:57 am
by feyd
if you're trying to return a square..

Code: Select all

function square($num)
&#123;
  return $num * $num;
&#125;