Bird
0
0

You want to sum all odd numbers from 1 to 9 using a PHP for loop. Which code correctly does this?

hard📝 Application Q9 of 15
PHP - Loops
You want to sum all odd numbers from 1 to 9 using a PHP for loop. Which code correctly does this?
Afor ($i = 1; $i <= 9; $i += 2) { $sum += $i; }
Bfor ($i = 0; $i <= 8; $i++) { if ($i % 2 == 1) $sum += $i; }
Cfor ($i = 1; $i < 9; $i += 2) { $sum += $i; }
Dfor ($i = 1; $i <= 8; $i += 2) { $sum += $i; }
Step-by-Step Solution
Solution:
  1. Step 1: Define loop range for odd numbers

    Odd numbers from 1 to 9 means start at 1, end at 9, step by 2.
  2. Step 2: Check which option matches this

    for ($i = 1; $i <= 9; $i += 2) { $sum += $i; } uses $i = 1; $i <= 9; $i += 2 which correctly sums odd numbers 1,3,5,7,9.
  3. Final Answer:

    for ($i = 1; $i <= 9; $i += 2) { $sum += $i; } -> Option A
  4. Quick Check:

    Sum odd numbers with step 2 from 1 to 9 = C [OK]
Quick Trick: Use step 2 starting at 1 for odd numbers [OK]
Common Mistakes:
  • Using wrong loop end condition
  • Starting from 0 instead of 1

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes