Why operators are needed in C - Performance Analysis
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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Addition operator in both functions.
- How many times: In
sum, addition happens once. Inmultiply, addition happensbtimes inside the loop.
Explain the growth pattern intuitively.
| Input Size (b) | Approx. Operations in multiply() |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of additions grows directly with b. More b means more work.
Time Complexity: O(b)
This means the time to multiply grows in a straight line with the size of b.
[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.
Understanding how operators affect time helps you explain why some code runs faster and how to write efficient programs.
"What if we replaced the loop in multiply() with a built-in multiplication operator? How would the time complexity change?"