0
0
Cprogramming~5 mins

Why functions are needed - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why functions are needed
O(n)
Understanding Time Complexity

We want to see how using functions affects the time it takes for a program to run.

Does breaking code into functions change how the program grows with bigger input?

Scenario Under Consideration

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 using a function.

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 n times, once for each number from 0 to n-1.
How Execution Grows With Input

As n gets bigger, the number of times the loop runs 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 grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Using a function makes the program slower or more complex."

[OK] Correct: Functions just organize code; they don't add extra loops or slow down the main work.

Interview Connect

Understanding how functions affect time helps you write clear code without worrying about hidden slowdowns.

Self-Check

"What if the function called itself recursively instead of using a loop? How would the time complexity change?"