Why C is widely used - Performance Analysis
We want to understand how the speed of C programs changes as the amount of work grows.
How does C handle bigger tasks efficiently?
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 simple loop.
Look at what repeats in the code.
- Primary operation: The loop that prints each number.
- How many times: It runs once for each number from 0 to n-1, so n times.
As n grows, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the input size.
Time Complexity: O(n)
This means if you double the input size, the work roughly doubles too.
[X] Wrong: "The loop runs faster because C is a fast language, so time complexity is less than O(n)."
[OK] Correct: Speed of the language does not change how many times the loop runs; time complexity counts how work grows, not how fast each step is.
Understanding how loops grow with input size is a key skill. It helps you write efficient C code and explain your thinking clearly.
"What if we added a nested loop inside the existing loop? How would the time complexity change?"