0
0
C++programming~5 mins

Function parameters in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function parameters
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n gets bigger, the number of print operations grows the same way.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Understanding how input parameters affect time helps you explain your code clearly and shows you think about efficiency.

Self-Check

"What if the function took two parameters and nested loops ran up to each? How would the time complexity change?"