What is C - Complexity Analysis
When learning about C programming, it helps to understand how the time a program takes can grow as it works with bigger inputs.
We want to see how the steps a C program does change when the input size changes.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
int main() {
int n = 5;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum: %d\n", sum);
return 0;
}
This code adds numbers from 1 to n and prints the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds numbers from 1 to n.
- How many times: It runs once for each number from 1 up to n.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: As n gets bigger, the number of additions grows in the same way, one step per number.
Time Complexity: O(n)
This means the time to finish grows directly with the size of the input n.
[X] Wrong: "The loop runs a fixed number of times no matter what n is."
[OK] Correct: The loop depends on n, so if n grows, the loop runs more times, making the program take longer.
Understanding how loops affect time helps you explain how your code will behave with bigger data, a skill that shows you think about efficiency.
"What if we replaced the for-loop with two nested loops each running n times? How would the time complexity change?"