Bird
0
0

How can you use a while loop to sum all numbers from 1 to 5 in Ruby? Choose the correct code.

hard📝 Application Q9 of 15
Ruby - Loops and Iteration
How can you use a while loop to sum all numbers from 1 to 5 in Ruby? Choose the correct code.
Asum = 0 num = 1 while num <= 5 do sum = num num += 1 end puts sum
Bsum = 0 num = 1 while num <= 5 do sum += num num += 1 end puts sum
Csum = 0 num = 0 while num < 5 do sum += num num += 1 end puts sum
Dsum = 0 num = 1 while num < 5 do sum += num num += 1 end puts sum
Step-by-Step Solution
Solution:
  1. Step 1: Understand summing numbers 1 to 5

    We add each number from 1 to 5 to sum.
  2. Step 2: Check loop conditions and sum updates

    sum = 0 num = 1 while num <= 5 do sum += num num += 1 end puts sum correctly loops from 1 to 5 inclusive, adding each to sum. Others either exclude 5, start at 0, or overwrite sum incorrectly.
  3. Final Answer:

    sum = 0 num = 1 while num <= 5 do sum += num num += 1 end puts sum -> Option B
  4. Quick Check:

    Loop from 1 to 5 adding to sum [OK]
Quick Trick: Add inside loop and increment counter [OK]
Common Mistakes:
  • Wrong loop range
  • Starting at 0 instead of 1
  • Overwriting sum instead of adding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes