Bird
0
0

Which Ruby for loop correctly prints all even numbers between 2 and 12 inclusive?

hard📝 Application Q8 of 15
Ruby - Loops and Iteration
Which Ruby for loop correctly prints all even numbers between 2 and 12 inclusive?
Afor i in 1..12 do puts i if i % 2 == 1 end
Bfor i in 2..12 do puts i if i.even? end
Cfor i in 2..12 do puts i if i % 2 != 0 end
Dfor i in 2..12 do puts i + 1 if i.even? end
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    Print even numbers from 2 to 12 inclusive.
  2. Step 2: Analyze options

    for i in 2..12 do puts i if i.even? end uses i.even? to filter even numbers correctly.
    for i in 1..12 do puts i if i % 2 == 1 end prints odd numbers.
    for i in 2..12 do puts i if i % 2 != 0 end prints odd numbers due to i % 2 != 0.
    for i in 2..12 do puts i + 1 if i.even? end adds 1 to even numbers, printing odd numbers instead.
  3. Final Answer:

    for i in 2..12 do puts i if i.even? end correctly prints even numbers from 2 to 12.
  4. Quick Check:

    Use i.even? or i % 2 == 0 to check even numbers [OK]
Quick Trick: Use i.even? to filter even numbers in loops [OK]
Common Mistakes:
  • Printing odd numbers instead of even
  • Incorrect condition logic
  • Modifying loop variable incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes