Bird
0
0

Which of the following is the correct way to write a while loop in Ruby that prints numbers from 1 to 3?

easy📝 Syntax Q3 of 15
Ruby - Loops and Iteration
Which of the following is the correct way to write a while loop in Ruby that prints numbers from 1 to 3?
A<pre>i = 1 while i <= 3 do puts i i++ end</pre>
B<pre>while i <= 3 puts i i += 1 end i = 1</pre>
C<pre>i = 1 while (i <= 3) { puts i i += 1 }</pre>
D<pre>i = 1 while i <= 3 puts i i += 1 end</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Initialize the loop variable

    Set i = 1 before the loop starts.
  2. Step 2: Use correct Ruby while syntax

    Ruby uses while condition do ... end or while condition ... end without braces.
  3. Step 3: Increment the loop variable properly

    Use i += 1 to increment; i++ is invalid in Ruby.
  4. Final Answer:

    i = 1
    while i <= 3
      puts i
      i += 1
    end
    is the correct syntax.
  5. Quick Check:

    Run the code to print 1, 2, 3 sequentially. [OK]
Quick Trick: Initialize before loop; use 'while condition do' and 'i += 1' [OK]
Common Mistakes:
MISTAKES
  • Placing initialization inside the loop
  • Using C-style increment operators like i++
  • Using braces {} instead of do...end

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes