Document

Activity 5

Problem 1

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

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

Solution

$j = "* ";

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

Output
*
* *
* * *
* * * *
* * * * *

Problem 2

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

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

Solution

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

{
echo "* ";
}
echo "< br>";
}

for($i = 5-1;$i >= 0;$i--){
for($j = 0;$j <= $i;$j++)

{
echo "* ";
}
echo "< br>";
}

Output
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*

Problem 3

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['num3'])){

$num3 = $_GET['num3'];
$sum = 0;
for($i = 0;$i <= $num3; $i++){

$sum += $i;

} echo "Sum between 1 to $num3 is: $sum";
}

Problem 4

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

Solution

echo "< table border='2'>";
for ($i = 1; $i <= 10; $i++) {

echo "< tr>";
for ($j = 1; $j <= 10; $j++) {
echo "< td>" . ($i * $j) . "< /td>";
}
echo "< /tr>";
} echo "";

Output
12345678910
2468101214161820
36912151821242730
481216202428323640
5101520253035404550
6121824303642485460
7142128354249566370
8162432404856647280
9182736455463728190
102030405060708090100