Challenge - 5 Problems
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP while loop?
Consider the following PHP code snippet. What will it print?
PHP
<?php $i = 3; while ($i > 0) { echo $i . " "; $i--; } ?>
Attempts:
2 left
💡 Hint
Remember the loop runs while the condition is true and $i decreases each time.
✗ Incorrect
The loop starts with $i = 3 and prints it. Then $i decreases by 1 each iteration until $i is 0, which stops the loop. So it prints '3 2 1 '.
❓ Predict Output
intermediate2:00remaining
How many times does this while loop run?
Look at this PHP code. How many times will the loop body execute?
PHP
<?php $count = 0; $num = 5; while ($num > 2) { $count++; $num--; } echo $count;
Attempts:
2 left
💡 Hint
Count how many times $num is greater than 2 before the loop stops.
✗ Incorrect
The loop runs while $num is 5,4,3 (3 times). When $num becomes 2, the condition fails and loop stops. So $count is 3.
🔧 Debug
advanced2:00remaining
Identify the error in this while loop code
This PHP code is supposed to print numbers 1 to 5 but causes an error or unexpected behavior. What is the problem?
PHP
<?php $i = 1; while ($i <= 5) echo $i . " "; $i++; ?>
Attempts:
2 left
💡 Hint
Check which statements are inside the loop and which are not.
✗ Incorrect
Without braces, only the first statement after while is inside the loop. The $i++ runs once after loop ends, so $i never changes inside loop, causing infinite loop.
🧠 Conceptual
advanced2:00remaining
What happens if the while loop condition is false initially?
Consider this PHP code snippet. What will be the output?
PHP
<?php $x = 0; while ($x > 0) { echo "Looping "; $x--; } echo "Done";
Attempts:
2 left
💡 Hint
Think about whether the loop body runs if the condition is false at start.
✗ Incorrect
Since $x is 0 and condition $x > 0 is false initially, the loop body never runs. Only 'Done' is printed.
❓ Predict Output
expert2:00remaining
What is the final value of $result after this while loop?
Analyze the PHP code below and find the value of $result after the loop finishes.
PHP
<?php $n = 4; $result = 1; while ($n > 0) { $result *= $n; $n--; } echo $result;
Attempts:
2 left
💡 Hint
This loop multiplies $result by $n each time, decreasing $n from 4 to 1.
✗ Incorrect
The loop calculates 4 * 3 * 2 * 1 = 24, so $result is 24 after the loop.