function problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
theweirdone
Forum Newbie
Posts: 2
Joined: Wed Jan 19, 2005 1:40 pm

function problem

Post 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...
User avatar
Wayne
Forum Contributor
Posts: 339
Joined: Wed Jun 05, 2002 10:59 am

Post 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!
theweirdone
Forum Newbie
Posts: 2
Joined: Wed Jan 19, 2005 1:40 pm

Post by theweirdone »

thats a good point... thanx... so thats one of my stupid mistakes... my function still doesn't work though...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

if you're trying to return a square..

Code: Select all

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