Bird
0
0

You want to print all even numbers from 2 to 10 using a while loop in PHP. Which code correctly does this?

hard📝 Application Q15 of 15
PHP - Loops

You want to print all even numbers from 2 to 10 using a while loop in PHP. Which code correctly does this?

?
A$i = 2; while ($i <= 10) { echo $i . ' '; $i += 2; }
B$i = 1; while ($i <= 10) { if ($i % 2 == 1) echo $i . ' '; $i++; }
C$i = 2; while ($i < 10) { echo $i . ' '; $i += 2; }
D$i = 0; while ($i <= 10) { echo $i . ' '; $i += 2; }
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct start and condition

    Start at 2 and include 10, so condition is $i <= 10.
  2. Step 2: Check increment and output

    Increment by 2 to get even numbers only, and echo with space.
  3. Step 3: Compare options

    $i = 2; while ($i <= 10) { echo $i . ' '; $i += 2; } matches all criteria exactly. $i = 1; while ($i <= 10) { if ($i % 2 == 1) echo $i . ' '; $i++; } prints odd numbers: 1 3 5 7 9. $i = 2; while ($i < 10) { echo $i . ' '; $i += 2; } misses 10. $i = 0; while ($i <= 10) { echo $i . ' '; $i += 2; } starts at 0, which is not requested.
  4. Final Answer:

    $i = 2; while ($i <= 10) { echo $i . ' '; $i += 2; } -> Option A
  5. Quick Check:

    Start=2, end=10, step=2 [OK]
Quick Trick: Start at 2, increment by 2, stop at 10 inclusive [OK]
Common Mistakes:
  • Starting at 0 or 1 instead of 2
  • Using < instead of <= to exclude 10
  • Not incrementing by 2 to get even numbers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes