Challenge - 5 Problems
Stride Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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: " ") }
Attempts:
2 left
💡 Hint
Remember that 'to' excludes the upper bound and the step is 3.
✗ Incorrect
The stride starts at 2 and adds 3 each time: 2, 5, 8. It stops before reaching 10.
❓ Predict Output
intermediate2: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: " ") }
Attempts:
2 left
💡 Hint
The 'through' keyword includes the end value, and step is negative.
✗ Incorrect
Starting at 10, subtract 4 each time: 10, 6, 2. The loop includes 2 because of 'through'.
🧠 Conceptual
advanced2:00remaining
Behavior of stride with zero step
What happens if you use stride(from: 1, to: 10, by: 0) in Swift?
Attempts:
2 left
💡 Hint
Think about what happens when the step never changes the value.
✗ Incorrect
A zero step causes a runtime error because the step must not be zero.
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
Count the numbers starting at 0, adding 7 each time, stopping before 20.
✗ Incorrect
The numbers are 0, 7, 14. The next would be 21 which is beyond 20, so count is 3.
❓ Predict Output
expert2: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: " ") }
Attempts:
2 left
💡 Hint
'through' includes the end value only if exactly reachable by the steps; consider floating-point.
✗ Incorrect
The stride generates 0.0, 0.3, 0.6, 0.9. The next value 1.2 exceeds 1.0, and 1.0 is not exactly reached.