For loop basics in Go - Time & Space Complexity
When we use a for loop, the program repeats some steps many times. Understanding how this repetition grows helps us know how fast or slow the program runs.
We want to find out how the number of repeated steps changes as the loop runs more times.
Analyze the time complexity of the following code snippet.
for i := 0; i < n; i++ {
fmt.Println(i)
}
This code prints numbers from 0 up to n-1, repeating the print step n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the for loop.
- How many times: Exactly n times, once for each loop cycle.
As n grows, the number of print steps grows the same way. If n doubles, the steps double too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print steps |
| 100 | 100 print steps |
| 1000 | 1000 print steps |
Pattern observation: The work grows directly with n, so more input means more steps in a straight line.
Time Complexity: O(n)
This means the time it takes grows in direct proportion to the number of times the loop runs.
[X] Wrong: "The loop runs instantly no matter how big n is."
[OK] Correct: Each loop step takes some time, so more steps mean more total time. The program does not skip the repeated work.
Knowing how loops affect time helps you explain your code clearly and shows you understand how programs grow with input size. This skill is useful in many coding situations.
"What if we added a nested loop inside this loop? How would the time complexity change?"