0
0
Cprogramming~5 mins

Splitting code into multiple files - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Splitting code into multiple files
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

Look for loops or repeated steps that take time.

  • Primary operation: The for-loop inside printNumbers that prints numbers.
  • How many times: It runs n times, once for each number.
How Execution Grows With Input

As n grows, the number of print steps grows the same way.

Input Size (n)Approx. Operations
1010 print steps
100100 print steps
10001000 print steps

Pattern observation: The work grows directly with n, no matter if code is split or not.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size n.

Common Mistake

[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.

Interview Connect

Understanding that splitting code helps keep things neat without slowing down your program is a useful skill to show.

Self-Check

"What if the function called inside the other file had a nested loop? How would that change the time complexity?"