Bird
0
0

What will be printed by this Swift code?

medium📝 Predict Output Q4 of 15
Swift - Loops
What will be printed by this Swift code?
let numbers = [2, 4, 6]
var sum = 0
for num in numbers {
    sum += num
}
print(sum)
AError
B24
C0
D12
Step-by-Step Solution
Solution:
  1. Step 1: Understand the loop operation

    The loop adds each number in the array to the sum variable.
  2. Step 2: Calculate the sum

    2 + 4 + 6 = 12, so sum becomes 12.
  3. Final Answer:

    12 -> Option D
  4. Quick Check:

    Sum of array elements = 12 [OK]
Quick Trick: Add each item inside the loop to sum [OK]
Common Mistakes:
  • Multiplying instead of adding
  • Printing sum before loop
  • Syntax errors in loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes