You have an array of integers and want to create a new array with only the even numbers using a for-in loop. Which code correctly does this?
hard📝 Application Q8 of 15
Swift - Loops
You have an array of integers and want to create a new array with only the even numbers using a for-in loop. Which code correctly does this?
Alet evens = []
for num in numbers {
if num % 2 == 0 {
evens.append(num)
}
}
Bvar evens = [Int]()
for num in numbers {
if num % 2 == 0 {
evens.append(num)
}
}
Cvar evens = [Int]
for num in numbers {
if num % 2 == 0 {
evens.append(num)
}
}
Dvar evens = Array
for num in numbers {
if num % 2 == 0 {
evens.append(num)
}
}
Step-by-Step Solution
Solution:
Step 1: Initialize an empty array correctly
var evens = [Int]()
for num in numbers {
if num % 2 == 0 {
evens.append(num)
}
} uses 'var evens = [Int]()' which correctly creates an empty integer array.
Step 2: Use for-in loop with condition and append
The loop checks if a number is even and appends it to evens array.
Final Answer:
var evens = [Int]()\nfor num in numbers {\n if num % 2 == 0 {\n evens.append(num)\n }\n} -> Option B
Quick Check:
Empty array init + append even numbers [OK]
Quick Trick:Initialize empty array with [Type]() before appending [OK]
Common Mistakes:
Using empty brackets [] without type
Missing parentheses in array initialization
Using Array without parentheses
Master "Loops" in Swift
9 interactive learning modes - each teaches the same concept differently