Bird
0
0

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

hard📝 Application Q8 of 15
Ruby - Loops and Iteration
You want to print all even numbers from 2 to 10 using a while loop in Ruby. Which code snippet correctly does this?
Anum = 2 while num <= 10 do puts num num += 2 end
Bnum = 1 while num <= 10 do puts num * 2 num += 1 end
Cnum = 2 while num < 10 do puts num num += 1 end
Dnum = 0 while num <= 10 do puts num num += 2 end
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want to print even numbers from 2 to 10 inclusive.
  2. Step 2: Check each option for correctness

    num = 2 while num <= 10 do puts num num += 2 end starts at 2, increments by 2, and stops at 10, printing 2,4,6,8,10 correctly. Others either print wrong numbers or go beyond 10.
  3. Final Answer:

    num = 2 while num <= 10 do puts num num += 2 end -> Option A
  4. Quick Check:

    Increment by 2 from 2 to 10 for even numbers [OK]
Quick Trick: Increment by 2 starting at 2 to print evens [OK]
Common Mistakes:
  • Starting at 1 and multiplying
  • Incrementing by 1 instead of 2
  • Wrong loop condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes