Function parameters - Time & Space Complexity
When we use function parameters, we want to know how the time to run the function changes as the input changes.
We ask: How does the function's work grow when the input values get bigger?
Analyze the time complexity of the following code snippet.
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 using a function with a parameter n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the function that prints numbers.
- How many times: It runs exactly n times, where n is the function parameter.
As n gets bigger, 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 in step with n. Double n, double the work.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the input size n.
[X] Wrong: "The function always takes the same time because it just prints numbers."
[OK] Correct: The time depends on how many numbers it prints, which is controlled by the input parameter n.
Understanding how function parameters affect time helps you explain how your code scales and shows you can think about efficiency clearly.
"What if the function printed numbers twice inside the loop? How would the time complexity change?"