0
0
Cprogramming~5 mins

Scope of variables - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Scope of variables
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code changes when we use variables in different places.

We want to know if where a variable is declared affects how long the program runs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

void example(int n) {
    int i;
    for (i = 0; i < n; i++) {
        int temp = i * 2;
        printf("%d\n", temp);
    }
}
    

This code prints double the value of numbers from 0 to n-1, declaring a variable inside the loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop runs from 0 to n-1.
  • How many times: The loop runs n times, and inside each loop, the variable temp is declared and used.
How Execution Grows With Input

Each time n grows, the loop runs more times, doing the same steps inside.

Input Size (n)Approx. Operations
10About 10 times the loop runs
100About 100 times the loop runs
1000About 1000 times the loop runs

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Declaring a variable inside the loop makes the program slower because it creates the variable every time."

[OK] Correct: In C, declaring a variable inside the loop does not add extra time for creation each time; it just allocates space on the stack each iteration, which is part of the loop's work already counted.

Interview Connect

Understanding how variable placement relates to time helps you write clear code without worrying about hidden slowdowns.

Self-Check

"What if we moved the variable temp declaration outside the loop? How would the time complexity change?"