Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Loops and Iteration
What will this Ruby code print?

result = 1
for i in 1..4 do
result *= i
end
puts result
A10
B24
C1
DError: undefined variable
Step-by-Step Solution
Solution:
  1. Step 1: Understand the loop and multiplication

    result starts at 1 and multiplies by i for i=1 to 4.
  2. Step 2: Calculate the product

    1*1=1, 1*2=2, 2*3=6, 6*4=24.
  3. Final Answer:

    24 -> Option B
  4. Quick Check:

    Factorial 4! = 24 [OK]
Quick Trick: Use *= to multiply and update variable inside loop [OK]
Common Mistakes:
MISTAKES
  • Using += instead of *=
  • Starting result at 0
  • Forgetting to print result

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes