CS-204 (PHP) Exercises
CS-204 (PHP) Exercises
1. Create a script that displays 1-2-3-4-5-6-7-8-9-10 on one line. There will be no hyphen (-)
at starting and ending position.
<?php
for($x=1; $x<=10; $x++)
{
if($x< 10)
{
echo "$x-";
}
else
{
echo "$x"."\n";
}
}
?>
**********************************************************
2. Create a script using a for loop to add all the integers between 0 and 30 and display the
total.
<?php
$sum = 0;
for($x=1; $x<=30; $x++)
{
$sum +=$x;
}
echo "The sum of the numbers 0 to 30 is $sum"."\n";
?>
**********************************************************
3. Create a script to construct the following pattern, using nested for loop.
*
**
***
****
*****
<?php
for($x=1;$x<=5;$x++)
{
1
for ($y=1;$y<=$x;$y++)
{
echo "*";
if($y< $x)
{
echo " ";
}
}
echo "<br>";
}
?>
**********************************************************
4. Create a script to construct the following pattern, using a nested for loop.
*
**
***
****
*****
*****
****
***
**
*
<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo "<br>";
}
for($i=$n; $i>=1; $i--)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
2
}
echo "<br>";
}
?>
**********************************************************
5. Write a program to calculate and print the factorial of a number using a for loop. The
factorial of a number is the product of all integers up to and including that number, so the
factorial of 4 is 4*3*2*1= 24.
<?php
$n = 6;
$x = 1;
for($i=1;$i<=$n-1;$i++)
{
$x*=($i+1);
}
echo "The factorial of $n = $x"."<Br>";
?>
**********************************************************
6. Write a PHP script that creates the following table using for loops. Add cellpadding="3px"
and cellspacing="0px" to the table tag.
1*1=1 1*2=2 1*3=3 1*4=4 1*5=5
2*1=2 2*2=4 2*3=6 2*4=8 2 * 5 = 10
3*1=3 3*2=6 3*3=9 3 * 4 = 12 3 * 5 = 15
4*1=4 4*2=8 4 * 3 = 12 4 * 4 = 16 4 * 5 = 20
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30
<html>
<body>
<table align="left" border="1" cellpadding="3" cellspacing="0">
<?php
for($i=1;$i<=6;$i++)
{
echo "<tr>";
for ($j=1;$j<=5;$j++)
3
{
echo "<td>$i * $j = ".$i*$j."</td>";
}
echo "</tr>";
}
?>
</table>
</body>
</html>
**********************************************************
7. Write a PHP script that creates the following table (use for loops).
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 10; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 10; $col++) {
$p = $col * $row;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>
**********************************************************