Bird
0
0

What will be the output of this Swift code?

medium📝 Predict Output Q5 of 15
Swift - Loops
What will be the output of this Swift code?
var sum = 0
for i in 1...5 {
    if i == 4 {
        break
    }
    sum += i
}
print(sum)
A6
B15
C10
D0
Step-by-Step Solution
Solution:
  1. Step 1: Trace the loop and break condition

    The loop adds numbers from 1 to 5, but breaks when i is 4, so it stops before adding 4.
  2. Step 2: Calculate sum before break

    Sum = 1 + 2 + 3 = 6; loop breaks before adding 4, so sum is 6.
  3. Step 3: Recheck sum calculation

    Wait, sum is 6, but 10 says 10. Let's re-examine: 1+2+3=6, so 6 is correct.
  4. Final Answer:

    6 -> Option A
  5. Quick Check:

    Break stops loop before adding 4, sum = 6 [OK]
Quick Trick: Break stops loop early, sum excludes 4 and 5 [OK]
Common Mistakes:
  • Adding all numbers ignoring break
  • Confusing break with continue
  • Miscounting sum before break

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes