0
0
Cprogramming~5 mins

Why operators are needed in C - Performance Analysis

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

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

How does the number of operations change when we use operators in code?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int sum(int a, int b) {
    return a + b;
}

int multiply(int a, int b) {
    int result = 0;
    for (int i = 0; i < b; i++) {
        result += a;
    }
    return result;
}
    

This code shows two functions: one adds two numbers directly using an operator, the other multiplies by adding repeatedly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Addition operator in both functions.
  • How many times: In sum, addition happens once. In multiply, addition happens b times inside the loop.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (b)Approx. Operations in multiply()
1010 additions
100100 additions
10001000 additions

Pattern observation: The number of additions grows directly with b. More b means more work.

Final Time Complexity

Time Complexity: O(b)

This means the time to multiply grows in a straight line with the size of b.

Common Mistake

[X] Wrong: "Multiplying two numbers is always as fast as adding them once."

[OK] Correct: Multiplication done by repeated addition takes more steps as the second number grows, so it is slower than a single addition.

Interview Connect

Understanding how operators affect time helps you explain why some code runs faster and how to write efficient programs.

Self-Check

"What if we replaced the loop in multiply() with a built-in multiplication operator? How would the time complexity change?"