0
0
Swiftprogramming~20 mins

For-in loop with ranges in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift For-in Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
Output of a for-in loop with a closed range
What is the output of this Swift code?
for i in 1...3 {
    print(i, terminator: " ")
}
Swift
for i in 1...3 {
    print(i, terminator: " ")
}
A1 2 3
B1 2
C0 1 2 3
D2 3 4
Attempts:
2 left
💡 Hint
The closed range operator '...' includes both the start and end values.
Predict Output
intermediate
1:30remaining
Output of a for-in loop with a half-open range
What does this Swift code print?
for i in 0..<4 {
    print(i, terminator: ",")
}
Swift
for i in 0..<4 {
    print(i, terminator: ",")
}
A0,1,2,
B0,1,2,3,4,
C1,2,3,4,
D0,1,2,3,
Attempts:
2 left
💡 Hint
The half-open range operator '..<' excludes the upper bound.
🔧 Debug
advanced
2:00remaining
Identify the error in the for-in loop with range
What error does this Swift code produce?
for i in 1...5 {
    if i = 3 {
        print("Three")
    }
}
Swift
for i in 1...5 {
    if i == 3 {
        print("Three")
    }
}
ASyntax error: Cannot assign to value: 'i' is a 'let' constant
BRuntime error: Index out of range
CSyntax error: Expected '==' in conditional
DNo error, prints 'Three' once
Attempts:
2 left
💡 Hint
Check the condition inside the if statement for correct comparison syntax.
🧠 Conceptual
advanced
1:30remaining
Number of iterations in a for-in loop with stride
How many times does this Swift loop run?
for i in stride(from: 0, to: 10, by: 3) {
    print(i)
}
Swift
for i in stride(from: 0, to: 10, by: 3) {
    print(i)
}
A10 times
B4 times
C5 times
D3 times
Attempts:
2 left
💡 Hint
The stride goes from 0 up to but not including 10, stepping by 3 each time.
Predict Output
expert
2:00remaining
Output of nested for-in loops with ranges
What is the output of this Swift code?
for i in 1...2 {
    for j in 1...2 {
        print(i * j, terminator: " ")
    }
}
Swift
for i in 1...2 {
    for j in 1...2 {
        print(i * j, terminator: " ")
    }
}
A1 2 2 4
B1 1 2 2
C2 4 1 2
D1 2 3 4
Attempts:
2 left
💡 Hint
Multiply each pair of i and j values in the nested loops.