0
0
Cprogramming~5 mins

Function parameters - 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++) {
        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 Repeating Operations

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.
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 in step with n. Double n, double 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 n.

Common Mistake

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

Interview Connect

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

Self-Check

"What if the function printed numbers twice inside the loop? How would the time complexity change?"