Bird
0
0

What is the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Loops and Iteration
What is the output of this Ruby code?

sum = 0
for i in 1..4
sum += i
end
puts sum
AError
B9
C0
D10
Step-by-Step Solution
Solution:
  1. Step 1: Understand the loop range and sum initialization

    The loop runs from 1 to 4, and sum starts at 0.
  2. Step 2: Calculate sum after each iteration

    sum = 0+1=1, then 1+2=3, then 3+3=6, then 6+4=10.
  3. Final Answer:

    10 -> Option D
  4. Quick Check:

    Sum of 1 to 4 is 10 [OK]
Quick Trick: Add numbers 1 through 4 to get 10 quickly [OK]
Common Mistakes:
MISTAKES
  • Forgetting to include last number 4
  • Starting sum at 1 instead of 0
  • Syntax errors in loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes