Header and source file organization - Time & Space Complexity
When organizing code into header and source files, it's important to understand how this affects the program's execution steps.
We want to see how the program's running time changes as the size of the input or code grows.
Analyze the time complexity of the following code snippet.
// header.h
#ifndef HEADER_H
#define HEADER_H
void printNumbers(int n);
#endif
// source.c
#include "header.h"
#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 separates the function declaration in a header file and the function definition in a source file. The function prints numbers from 1 to n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside
printNumbersthat prints numbers. - How many times: It runs exactly
ntimes, once for each number from 1 ton.
As n grows, the number of print operations grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
Pattern observation: The work increases evenly as n increases. Double the input, double the work.
Time Complexity: O(n)
This means the program takes longer in direct proportion to the input size n.
[X] Wrong: "Splitting code into header and source files makes the program run faster."
[OK] Correct: Organizing code this way helps keep code clean and manageable, but it does not change how many steps the program takes when running.
Understanding how code organization relates to program speed shows you think about both writing clean code and how it runs, a useful skill in real projects.
"What if the function printed numbers twice inside the loop? How would the time complexity change?"