Document Document

Loops


1. Write a PHP script that will output the following loop:

*
* *
* * *
* * * *
* * * * *


Solution

$x = "*";
for ($i = 0; $i< 5; $i++){
 echo"$x";
 echo"<br>"; 
 $x .="* ";
}

Output:
*
* *
* * *
* * * *
* * * * *




2. Write a PHP script that will output the following loop:


*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*



Solution

for ($i = 0; $i <= 5; $i++){
 for($j = 0; $j < $i; $j++){
  echo "* ";
 }echo"<br>";
}
for ($i = 5; $i >= 0; $i--){
 for($j = 0; $j<$i; $j++){
  echo "* ";
 }echo "<br>";
}

Output:
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*





3. Create a script using a for loop to add all the integers between 0 and 10 and display the total. the range should be user inputted.

Solution

if(isset($_GET["num"])){
 $num = $_GET["num"];
 $output = 0;
 for($i = 1; $i<=$num;$i++){
  $output+=$i;
 }
 echo"$output";
}





4. Write a PHP script that creates the following table (use for loops).



Solution

echo "<table class = 'numTable'>";
 for($i=1;$i<=10;$i++){
  echo "<tr>";
  for($j=$i;$j<=$i*10;$j+=$i){
   echo"<td><strong>$j</strong></td>";
  }echo "</tr><br>";
 }echo"</table>";

Output:









12345678910
2468101214161820
36912151821242730
481216202428323640
5101520253035404550
6121824303642485460
7142128354249566370
8162432404856647280
9182736455463728190
102030405060708090100