Calculate a square of a number then cube it

I am so confused… I am trying to create a function to calculate the square of a number THEN in another function cube the number it in a table of 10 rows/columns… here is what I have… :o

$begin = 3;
function calculate()
{
global $begin;
echo “

”;
for ($num = 1; $num <= 10; $num++ )
{
$cell = $begin * $num;
echo “” . $cell . “”;
}
echo “”;
}
echo “”;
while ( $begin <= 12 )
{
calculate();
$begin++;
}
echo “
”;

First ditch global variables (It’s a bad habit to get into in my opinion) and learn variable scope : http://php.net/manual/en/language.variables.scope.php

This will help you utilize functions to their full potential. I really not sure what you wanted, but I took my best guess. If I didn’t get it right, it will give good practice in getting what you really wanted.

This is the way I would go about doing it:
[php]<?php
$squareNum = array(); // Create the square array:
$cubeNum = array(); // Create the cube array:
/* Create a function to do calculations /
function sqrNum($myNum) {
for($x=0; $x<10; $x++) {
$squareNum[] = pow($myNum, 2); // Square the Number:
$myNum +=1; // Increment it to next number:
}
return $squareNum; // Return the Argument
}
function cubeNum($myNum) {
for($x=0; $x<10; $x++) {
$cubeNum[] = pow($myNum, 3); // Cube the Number:
$myNum +=1; // Increment to the next number:
}
return $cubeNum; // Return the Argument
}
$myNum = 3; // The Number
$squareNum = sqrNum($myNum); // Call the square function:
$cubeNum = cubeNum($myNum); // Call the cube function:
/
The above assigns the return arrays to their respective arrays */
?>

My Calculations table, th, td { border: 1px solid #000; border-collapse: collapse; } th, td { padding: 5px; text-align: right; } <?php
$tempNum = $myNum;
for( $x=0; $x<10; $x++) {
  echo "<tr>\n";
  echo '<td>' . $tempNum . '</td>' . "\n";
  echo '<td>' . $squareNum[$x] . '</td>'. "\n";
  echo '<td>' . $cubeNum[$x] . '</td>'. "\n";
  echo "</tr>\n";
  $tempNum += 1;
}

?>
Number Squared Cubed
[/php]

I’ve comment it the best I could without going overboard, I think some of it is self-explanatory. I hope. :wink:

P.S. This could be modified where you could tighten the code where you only use 1 function and I will give you a hint. It would involve using two arguments when calling the function and making some modification to the function. Then simply return the results in a array.

Thank you so much! I will play around with it… I really want to understand what you did and learn it :slight_smile: I appreciate your time!!!

Sponsor our Newsletter | Privacy Policy | Terms of Service