Follow:  Follow PHPExercises on Twitter  Follow us on Facebook

PHP Control Structures Ex. #3: Simple For Loop

Loops are very useful in creating lists and tables. In this PHP exercise, you will use a loop to create a list of equations for squares.

Using a for loop, write a script that will send to the browser a list of squares for the numbers 1-12.
Use the format, "1 * 1 = 1", and be sure to include code to print each formula on a different line.

 

Comments

Not to be rude, but I think that this lesson could use a little re-wording. I was a little confused, as I was assuming you wanted actual squares like table squares. making a list would probably be a little easier to understand. Good work with the site, I really enjoy it.

Glad you enjoy the site. Regarding this exercise, we feel that giving the example equation "1*1=1" makes it clear what kind of squares are being requested.

hi... Probably no one is reading this again cos most comments were last years. I tried d exercise but in ur answer- i didnt find d script for d new lines. Here is mine- i got d ans but worried if my < ol> is unneccessary:
for($a=1;$a <= 12; $a++){
$b= $a*$a;
echo "< ol>$a*$a = $b < /ol>;
}
good work here.. Can more exercises be created? Thx!

$foo = 1;
while($foo <= 12) {
echo "$foo * $foo = ". pow($foo, 2)."";
$foo++;
}

a hardened javascript developer, I really want to learn how to bring more backend experience to my users, not to mention learning how everything works behind the scenes, and being able to get my hands dirty in various CMSs when things go awry. this site is great for getting sanding off the awkward edges between the languages, while still hammering home the basics. excellent! : )

  1. <!DOCTYPE html>
  2. <HTML>
  3.     <HEAD>
  4.         <TITLE>Squares for the Numbers 1-12</TITLE>
  5.     </HEAD>
  6.     <BODY>
  7.         <?php
  8.             for($x=1; $x<=12; $x++)
  9.             {
  10.                 echo "$x x $x = ".($x*$x)."<BR />";
  11.             }
  12.         ?>
  13.     </BODY>
  14. </HTML>

<?php
	$i = 1;
	for ($i = 1; $i <= 12; $i++){
		$f = pow($i,2);
		echo "$i squared is: $f";
	}
?>

echo "$x * $x = $result \n"

Why you have used BR tag and \n.
Both are for new line. Why do you used both? However, BR tag is enough.. Am I right?

This is how I printed the quotes.


<?php 

for ($i=1; $i<13; $i++){
	echo "\"$i * $i = ".($i*$i)."\"";
}

?>

Used the pow() function to get the results.

  1. <!DOCTYPE HTML>
  2. <html>
  3. 	<head>
  4. 		<meta http-equiv="content-type" content="text/html; charset=utf-8">
  5. 		<title>Phpex-10</title>
  6. 	</head>
  7. 	<body>
  8. 		<?php
  9. 			for ($i = 1; $i < 13; $i++) {
  10. 				echo "$i * $i = " . pow($i, 2) . "<br />";
  11. 			}
  12. 		?>
  13. 	</body>
  14. </html>