Why modular programming is needed in C - Performance Analysis
When we write programs in small parts or modules, it helps us manage complexity better.
We want to see how breaking code into modules affects how long the program takes to run.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void printNumbers(int n) {
for (int i = 1; i <= n; i++) {
printf("%d\n", i);
}
}
int main() {
printNumbers(5);
return 0;
}
This code prints numbers from 1 to n using a separate function, showing modular design.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the function
printNumbersthat prints numbers. - How many times: It runs exactly n times, once for each number from 1 to n.
As n grows, the number of times the loop runs 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 n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the program grows in a straight line with the size of the input.
[X] Wrong: "Modular programming makes the program slower because it adds extra function calls."
[OK] Correct: The extra function calls are very small compared to the benefits of clear, manageable code. The main work still depends on the loops or operations inside the modules.
Understanding how modular code affects time helps you explain your design choices clearly and shows you think about both code quality and performance.
"What if the function printNumbers called another function inside the loop that also runs n times? How would the time complexity change?"