Use cases - Time & Space Complexity
When we look at use cases in programming, we want to know how the time a program takes changes as the input grows.
We ask: How does the program's work increase when we give it more data?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void printNumbers(int n) {
for (int i = 0; i < n; i++) {
printf("%d\n", i);
}
}
int main() {
printNumbers(5);
return 0;
}
This code prints numbers from 0 up to n-1, showing a simple use case of a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each number.
- How many times: It runs exactly n times, once for each number from 0 to n-1.
As n grows, the number of print operations 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 input size; double the input, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the input.
[X] Wrong: "The loop runs faster because it just prints numbers quickly."
[OK] Correct: The speed of printing doesn't change the fact that the loop runs once per input item, so time still grows with n.
Understanding how simple loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.
"What if we added a nested loop inside the existing loop? How would the time complexity change?"