Function parameters in C++ - 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++) {
std::cout << i << std::endl;
}
}
int main() {
printNumbers(5);
return 0;
}
This function prints numbers from 0 up to n-1, where n is given as a parameter.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints numbers.
- How many times: It runs exactly n times, where n is the input 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 with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the input size.
[X] Wrong: "Function parameters do not affect time because they are just values passed in."
[OK] Correct: The size or value of parameters often controls how many times the function repeats work, so they do affect time.
Understanding how input parameters affect time helps you explain your code clearly and shows you think about efficiency.
"What if the function took two parameters and nested loops ran up to each? How would the time complexity change?"