Bird
0
0

What is the output of this Swift code?

medium📝 Predict Output Q13 of 15
Swift - Loops
What is the output of this Swift code?
var sum = 0
for number in 1..<5 {
  sum += number
}
print(sum)
A10
B15
C14
DError
Step-by-Step Solution
Solution:
  1. Step 1: Identify the range and loop values

    The range 1..<5 includes 1, 2, 3, 4 (excluding 5).
  2. Step 2: Calculate the sum of these numbers

    Sum = 1 + 2 + 3 + 4 = 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Sum of 1 to 4 = 10 [OK]
Quick Trick: Half-open range excludes last number; sum 1+2+3+4 = 10 [OK]
Common Mistakes:
  • Including 5 in the sum
  • Adding numbers incorrectly
  • Confusing closed and half-open ranges

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes