Print function for output in Swift - Time & Space Complexity
Let's see how the time it takes to print something grows as we print more items.
We want to know how the print function's work changes when printing many values.
Analyze the time complexity of the following code snippet.
for number in 1...n {
print(number)
}
This code prints numbers from 1 up to n, one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the loop.
- How many times: Exactly n times, once for each number from 1 to n.
As n grows, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the number of items to print.
Time Complexity: O(n)
This means the time to print grows in a straight line as you print more numbers.
[X] Wrong: "Printing is instant and does not depend on how many items we print."
[OK] Correct: Each print takes some time, so printing more items takes more total time.
Understanding how simple loops like printing scale helps you explain how programs handle bigger tasks step by step.
"What if we printed only every other number instead of all numbers? How would the time complexity change?"