Activity 5

Problem 1

Write a PHP script the will output the following using loop.

Solution:

for ($i = 1; $i <= 5; $i++) {

      echo str_repeat('*', $i) .<br>;

}

Output:

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

Problem 2

Write a PHP script the will output the following using loop.

Solution:

$rows = 10;

      for ($i = 1; $i <= $rows; $i++) {

           if ($i <= 5) {

               for ($j = 1; $j <= $i; $j++) {

               echo "* ";

                   }

           } else {

               for ($j = 1; $j <= $rows - $i + 1; $j++) {

               echo "* ";

               }

           }

           echo "<br>";

}

Output:

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

Problem 3

Write a PHP script the will output the following using loop.

Solution:

if(isset($_GET['num'])) {

      $start = 1;

      $end = (int) $_GET['num'];

      $total = 0;

      for ($i = $start; $i <= $end; $i++) {

          $total += $i;

      }

      echo "The sum of numbers $start to $end is $total.<br>";

}

Output:



Problem 4

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

Solution:

$rows = 10;

$columns = 10;

    for ($i = 1; $i <= $rows; $i++) {

        echo "<tr>";

        for ($j = 1; $j <= $columns; $j++) {

         $value = $i * $j;v

         echo "<td>$value<td>";

        }

         echo "<tr>";

}

Output:

12345678910
2468101214161820
36912151821242730
481216202428323640
5101520253035404550
6121824303642485460
7142128354249566370
8162432404856647280
9182736455463728190
102030405060708090100