Working with Loops - Exercise

Contact Us or call 1-877-932-8228
Working with Loops - Exercise

Working with Loops

Duration: 10 to 15 minutes.
  1. Open FlowControl/Exercises/Loops.php in your editor.
  2. Under the while header, use a while loop to output all the even numbers that are less than or equal to 100.
  3. Under the for header, use a for loop to output all the odd numbers that are less than or equal to 100.

Challenge

In both loops, skip all numbers that are divisible by 3. Be careful not to get caught in an infinite loop.

Solution:

FlowControl/Solutions/Loops.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Loops</title>
</head>

<body>
<h2>while</h2>
<ul>
<?php
	$a=2;
	while ($a <= 100)
	{
		echo "<li>$a</li>";
		$a+=2;
	}
?>
</ul>

<h2>for</h2>
<ul>
<?php
	for ($a=1; $a <= 100; $a+=2)
	{
		echo "<li>$a</li>";
	}
?>
</ul>
</body>
</html>

Challenge Solution:

FlowControl/Solutions/Loops-challenge.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Loops</title>
</head>

<body>
<h2>while</h2>
<ul>
<?php
	$a=2;
	while ($a <= 100)
	{
		if ($a % 3 == 0)
		{
			$a+=2;
			continue;
		}
		echo "<li>$a</li>";
		$a+=2;
	}
?>
</ul>

<h2>for</h2>
<ul>
<?php
	for ($a=1; $a <= 100; $a+=2)
	{
		if ($a % 3 == 0)
		{
			continue;
		}
		echo "<li>$a</li>";
	}
?>
</ul>
</body>
</html>
Next