0
0
Cprogramming~5 mins

Header and source file organization - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Header and source file organization
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As n grows, the number of print operations grows in a straight line.

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

Pattern observation: The work increases evenly as n increases. Double the input, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in direct proportion to the input size n.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if the function printed numbers twice inside the loop? How would the time complexity change?"