Splitting code into multiple files - Time & Space Complexity
When we split code into multiple files, we want to know if it changes how long the program takes to run.
Does breaking code into parts affect the speed of the program?
Analyze the time complexity of this simple program split into two files.
// file1.c
#include <stdio.h>
void printNumbers(int n);
int main() {
printNumbers(5);
return 0;
}
// file2.c
#include <stdio.h>
void printNumbers(int n) {
for (int i = 1; i <= n; i++) {
printf("%d\n", i);
}
}
This code prints numbers from 1 to n, but the printing function is in a separate file.
Look for loops or repeated steps that take time.
- Primary operation: The for-loop inside
printNumbersthat prints numbers. - How many times: It runs n times, once for each number.
As n grows, the number of print steps grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print steps |
| 100 | 100 print steps |
| 1000 | 1000 print steps |
Pattern observation: The work grows directly with n, no matter if code is split or not.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size n.
[X] Wrong: "Splitting code into files makes the program slower because it adds extra steps."
[OK] Correct: Splitting code into files is about organizing code, not about how many times loops run. The main work still depends on the loops, not the file structure.
Understanding that splitting code helps keep things neat without slowing down your program is a useful skill to show.
"What if the function called inside the other file had a nested loop? How would that change the time complexity?"