0
0
Swiftprogramming~20 mins

Stride for custom step in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Stride Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of stride with positive step
What is the output of this Swift code using stride with a positive step?
Swift
for number in stride(from: 2, to: 10, by: 3) {
    print(number, terminator: " ")
}
A2 5 8
B2 3 4 5 6 7 8 9
C2 6 10
D3 6 9
Attempts:
2 left
💡 Hint
Remember that 'to' excludes the upper bound and the step is 3.
Predict Output
intermediate
2:00remaining
Output of stride with negative step
What is the output of this Swift code using stride with a negative step?
Swift
for number in stride(from: 10, through: 2, by: -4) {
    print(number, terminator: " ")
}
A10 6 2
B10 6
C10 8 6 4 2
D10 2
Attempts:
2 left
💡 Hint
The 'through' keyword includes the end value, and step is negative.
🧠 Conceptual
advanced
2:00remaining
Behavior of stride with zero step
What happens if you use stride(from: 1, to: 10, by: 0) in Swift?
AThe loop does not run at all.
BThe program runs an infinite loop printing 1 endlessly.
CThe program throws a runtime error due to zero step.
DThe loop runs once printing 1 and stops.
Attempts:
2 left
💡 Hint
Think about what happens when the step never changes the value.
Predict Output
advanced
2:00remaining
Count of elements generated by stride
How many numbers does this Swift stride generate?
Swift
let numbers = Array(stride(from: 0, to: 20, by: 7))
print(numbers.count)
A4
B3
C2
D5
Attempts:
2 left
💡 Hint
Count the numbers starting at 0, adding 7 each time, stopping before 20.
Predict Output
expert
2:00remaining
Output of stride with floating point step
What is the output of this Swift code using stride with a floating point step?
Swift
for value in stride(from: 0.0, through: 1.0, by: 0.3) {
    print(String(format: "%.1f", value), terminator: " ")
}
A0.0 0.3 0.6 0.9 1.2
B0.0 0.3 0.6 0.9 1.1
C0.0 0.3 0.6 0.9 1.0
D0.0 0.3 0.6 0.9
Attempts:
2 left
💡 Hint
'through' includes the end value only if exactly reachable by the steps; consider floating-point.