Bird
0
0

You want to print numbers from 1 to 5 using loop. Which code correctly does this?

hard📝 Application Q8 of 15
Ruby - Loops and Iteration
You want to print numbers from 1 to 5 using loop. Which code correctly does this?
Ai = 1 loop do puts i break if i == 5 i += 1 end
Bi = 1 loop do puts i i += 1 break if i > 5 end
Ci = 1 loop do break if i > 5 puts i i += 1 end
Di = 1 loop do puts i i += 1 end
Step-by-Step Solution
Solution:
  1. Step 1: Check each option's output

    i = 1 loop do puts i break if i == 5 i += 1 end prints 1 to 5 but breaks after printing 5, so correct.
    i = 1 loop do puts i i += 1 break if i > 5 end breaks after i > 5, so prints 1 to 5 correctly.
    i = 1 loop do break if i > 5 puts i i += 1 end breaks before printing when i > 5, so prints 1 to 5.
    i = 1 loop do puts i i += 1 end never breaks, infinite loop.
  2. Step 2: Identify the best practice

    i = 1 loop do break if i > 5 puts i i += 1 end breaks before printing when i > 5, so it prints exactly 1 to 5 without extra checks after printing.
  3. Final Answer:

    Option C correctly prints numbers 1 to 5 using loop -> Option C
  4. Quick Check:

    Break before printing stops at 5 = correct loop [OK]
Quick Trick: Break before printing avoids extra output [OK]
Common Mistakes:
MISTAKES
  • Breaking after printing causes off-by-one output
  • Forgetting to increment counter
  • Not including break causing infinite loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes