7. Fibonacci Series: Create a program that will print out a Fibonacci series,
e.g. 1 1 2 3 5 8 13 21 34 …
Answer :
function fibo($fnum)
{
$a = 1;
$b = 1;
$c = 0;
echo $a." ".$b;
for($i=0;$i<$fnum-2;$i++) {
$c = $a + $b;
$a = $b;
$b = $c;
echo $c;
}
}
$num = 8;
echo $num <br>;
fibo($num);
function fibo($fnum)
{
$a = 1;
$b = 1;
$c = 0;
echo $a." ".$b;
for($i=0;$i<$fnum-2;$i++) {
$c = $a + $b;
$a = $b;
$b = $c;
echo $c;
}
}
$num = 8;
echo $num <br>;
Part 1 Exam
3. Evens, Odds, and Dozens: Create a program that will count
down to 0 from a given number—$start. For each number, print the number
and then print (“ is even”) if it is even and (“ is odd”), if it is
odd. In addition, if the number is a multiple of 12, print the number
of dozens that it represents. For example if $start=27, the output
might look like:
26 is even.
25 is odd.
24 is even. 24 is 2 dozen.
23 is odd. …
27 is odd.
Answer :
function OddEven($testNum)
{
if($testNum % 2 == 0)
{
echo " is Even";
}
else
{
echo " is Odd";
}
}
$start = 20;
do
{
echo $start <br>;
OddEven($start);
$start--;
}
while($start>=1)
Part 1 Exam
2. “Mod” calculation: The mod (%) operator in PHP calculates the remainder when $a is divided by $b. Create a program that calculates the remainder by repeatedly subtracting $b from $a until it can no longer be subtracted (i.e. stop subtracting when $a is less than $b). Print out the remainder, nicely formatted (e.g. if $a=7 and $b=2 you might print “7 mod 2 = 1”).
Answer:
function mod($modB){
if($modB % 2 == 0)
{
echo "0";
}
else
{
echo "1";
}
}
$a = 2;
$b = 7;
do
{
echo '$b % $a =';
mod($b);
$b -= $a;
}
while($b > 1)
Part 1 Exam
2. “Mod” calculation: The mod (%) operator in PHP calculates the remainder when $a is divided by $b. Create a program that calculates the remainder by repeatedly subtracting $b from $a until it can no longer be subtracted (i.e. stop subtracting when $a is less than $b). Print out the remainder, nicely formatted (e.g. if $a=7 and $b=2 you might print “7 mod 2 = 1”).
Answer:
function mod($modB)
{
if($modB % 2 == 0)
{
echo "0";
}
else
{
echo "1";
}
}
$a = 2;
$b = 7;
do
{
echo '$b % $a =';
mod($b);
$b -= $a;
}
while($b > 1)
Part 1 Exam
1. Leap Year Calculation: Given a variable called $year, create a program that will print out “<xxxx> is a leap year” or “<xxxx> is not a leap year” (where <xxxx> is the value of $year). Use the following rules to determine if a year is a leap year: if the year is divisible by 4 then it is a leap year, unless it is also divisible by 100 (in which case it is not a leap year), unless it is divisible by 400 (in which case it is a leap year).
Answer:
$year = 2012;
if($year % 4 == 0)
{
if($year % 100 == 0)
{
if($year % 400 == 0)
{
echo "Leapyear";
}
else
{
echo "Not a Leapyear";
}
}
else
{
echo "Leapyear";
}
}
else
{
echo "Not a Leapyear";
}
No comments:
Post a Comment