0
0
Cprogramming~5 mins

Macro with arguments - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Macro with arguments
O(n)
Understanding Time Complexity

We want to see how the time it takes to run code with macros that have arguments changes as input grows.

How does using a macro with arguments affect the number of steps the program does?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

#include <stdio.h>

#define SQUARE(x) ((x) * (x))

int main() {
    int n = 5;
    for (int i = 0; i < n; i++) {
        printf("%d\n", SQUARE(i));
    }
    return 0;
}

This code uses a macro with an argument to calculate the square of numbers from 0 to n-1 and prints them.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop runs n times, calling the macro each time.
  • How many times: The macro expands and runs once per loop iteration, so n times.
How Execution Grows With Input

Each time n grows, the loop runs more times, and the macro runs that many times too.

Input Size (n)Approx. Operations
10About 10 squares calculated and printed
100About 100 squares calculated and printed
1000About 1000 squares calculated and printed

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input size increases.

Common Mistake

[X] Wrong: "Macros with arguments run only once, so they don't affect time complexity."

[OK] Correct: Each time the macro is used in code, it expands and runs, so if inside a loop, it runs multiple times.

Interview Connect

Understanding how macros with arguments behave helps you explain how code runs and grows, a useful skill for writing efficient programs.

Self-Check

"What if we replaced the macro with a function call? How would the time complexity change?"