PHP Multiple Choice Questions on “For Loops – 2”.
1. What will be the output of the following PHP code?
-
-
for ($x = 1; $x < 10; $x++)
-
for ($y = 1; $y < 5; $y++)
-
print "Hello";
-
?>
a) Hello….36 times
b) Hello….45 times
c) Hello….50 times
d) Hello….40 times
Answer: a
Clarification: 9*4 times is printed.
2. What will be the output of the following PHP code?
-
-
for ($count = 1; $count != 20;$count++)
-
{ -
print $count;
-
$count++;
-
} -
?>
a) Infinite
b) 123…….20
c) 1357…19
d) 13579…21
Answer: a
Clarification: Condition always fails as count takes only odd numbers.
3. What will be the output of the following PHP code?
-
-
for ($count = 1; $count < 20; $count++);
-
print $count;
-
?>
a) 20
b) 19
c) 12345678910….19
d) 12345678910….1920
Answer: a
Clarification: The for loop has no body, it just runs till condition is satisfied.
4. What will be the output of the following PHP code?
-
-
for ($count = 0; $count < 3;$count++);
-
{ -
print "hi";continue;print "hello";
-
} -
?>
a) hihihi
b) hihellohihellohihello
c) hellohellohello
d) hi
Answer: a
Clarification: When continue is encountered it skips to the next iteration.
5. What will be the output of the following PHP code?
-
-
for ($count = 0; $count<3;$count++);
-
{ -
print "hi";break;print "hello";
-
} -
?>
a) hihihi
b) hihellohihellohihello
c) hellohellohello
d) hi
Answer: d
Clarification: When break is encountered it leaves the loop.
6. What will be the output of the following PHP code?
-
-
for(++$i; ++$i; ++$i)
-
{ -
print $i;
-
if ($i == 4)
-
break;
-
} -
?>
a) 24
b) 134
c) 1234
d) 1
Answer: a
Clarification: The order of execution is initialization, check, increment/decrement, check, increment/decrement, check, increment/decrement….so on.
7. What will be the output of the following PHP code?
-
-
for ($i = 0;$i = -1;$i = 1)
-
{ -
print $i;
-
if ($i != 1)
-
break;
-
} -
?>
a) 0
b) infinite loop
c) -1
d) 1
Answer: c
Clarification: The order of execution is initialization, check, increment/decrement, check, increment/decrement, check, increment/decrement….so on.
8. What will be the output of the following PHP code?
-
-
for(;;)
-
{ -
print "10";
-
} -
?>
a) 10
b) infinite loop
c) no output
d) error
Answer: b
Clarification: There is no check condition to stop the execution of the loop.
9. What will be the output of the following PHP code?
-
-
for ($i = 0; $i < 3; $i++)
-
{ -
for($j = $i; $j > 0; $j--)
-
print " ";
-
for($k = $j; $k < 3; $k++)
-
print "*";
-
print "n";
-
} -
?>
a)
*
**
***
b)
*** ** *
c)
* ** ***
d) error
Answer: a
Clarification: Follow the trace of i, j prints 3 – i no of spaces for each i, k prints i stars for each loop.
10. What will be the output of the following PHP code?
-
-
for ($i = 0; -5 ; $i++)
-
{ -
print"i";
-
if ($i == 3)
-
break;
-
} -
?>
a) 0 1 2 3 4
b) 0 1 2 3
c) 0 1 2 3 4 5
d) error
Answer: b
Clarification: The break statement after breaks the loop after i=3, does not print anymore.
