Jump to content

Php Newbie's Question For A Multiplication Table


ayaya

Recommended Posts

Hello, I want to have a multiplication table only from 3 to 7. Please see my code, first:

 

<?php
function fun($startNum,$endNum=9,$order){
 if($startNum == ""){
  echo "fun () // repeat an alert six times: <br>";
  for($j=1;$j<=6;$j++){
  echo "please enter at least one number!"."<br>";
  }
 }
 else if($order=="resort"){
   //multiplication table in descendant order
 for($j=$endNum;$j>=$startNum;$j--){
 for($l=1;$l<=$j;$l++){
  print "$l*$j=".$j*$l." ";
 }
   echo "<br />";
   }
  }
 else {
  //multiplication table in ascendant order
  for($j=$startNum;$j<=$endNum;$j++){
 for($l=1;$l<=$j;$l++){
  print "$l*$j=".$j*$l." ";
 }
  echo "<br />";
  }
 }
}


echo "multiplication table: <br>";
fun(1);

echo "<br />";
echo "ascendant from 3 to 7: <br>";
fun(3,7);

echo "<br />";
echo "descendant from 7 to 3: <br>";
fun(3,7,"resort");

    echo "<br />";
fun();

?>

 

The result of this code is:

post-135692-0-40637400-1356822099_thumb.png

 

But I want to have this:

post-135692-0-47645200-1356822185_thumb.png

 

So I change my code to this:

else if($order=="resort"){
  //multiplication table in descendant order
   $l=$startNum;
   for($j=$endNum;$j>=$startNum;$j--){
 for($l=$j;$l<=$j;$l--){
  print "$l*$j=".$j*$l." ";
 }
   echo "<br />";
   }
  }

 

But it doesnt work! it's a dead loop... why?

Can anyone help me?

Thanks in advance

hehe, finally i did it myself! i'm very happy :happy-04:

else if($order=="resort"){
//multiplication table in descendant order

for($j=$endNum;$j>=$startNum;$j--){
 for($l=$startNum;$l<=$j;$l++){
 print "$l*$j=".$j*$l." ";
 }
echo "<br />";
}
}
else {
//multiplication table in ascendant order
for($j=$startNum;$j<=$endNum;$j++){
 for($l=$startNum;$l<=$j;$l++){
 print "$l*$j=".$j*$l." ";
 }
echo "<br />";
}
}

Not entirely sure how to fix your problem but one thing I picked up on is that if you want in your function to have a non-required parameter you need to either do = NULL or = '', otherwise when you execute that function without it, it will have an error.

 

Examples:

function fun($var,$var2,$var3){
//Do stuff
}

fun('value','value2');
//Will fail

function fun2($var,$var2 = NULL,$var3 = ''){
//Do stuff
}

fun2('value');
//Will Run

 

Hope this helps

Timothy

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.