Bird
0
0

Identify the error in this Ruby code:

medium📝 Debug Q6 of 15
Ruby - Loops and Iteration
Identify the error in this Ruby code:
counter = 0
until counter > 4 do
  puts counter
  counter = counter - 1
end
AThe <code>puts</code> statement is incorrect
BThe condition should be <code>counter < 4</code>
CMissing <code>end</code> keyword
DThe counter decreases causing an infinite loop
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop condition and update

    The loop runs until counter > 4 becomes true.
  2. Step 2: Check counter update

    Counter starts at 0 and is decremented each iteration (counter = counter - 1), so it moves away from the exit condition.
  3. Step 3: Identify error

    Since counter decreases, it will never become > 4, causing an infinite loop.
  4. Final Answer:

    The counter decreases causing an infinite loop -> Option D
  5. Quick Check:

    Counter must move towards exit condition to avoid infinite loop [OK]
Quick Trick: Ensure loop variable moves toward exit condition [OK]
Common Mistakes:
  • Decrementing counter when it should increment
  • Incorrect loop condition logic
  • Forgetting to update loop variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes