0
0
C++programming~5 mins

Scope of variables in C++ - Time & Space Complexity

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

We want to see how the time cost changes when we use variables in different places in code.

How does where a variable is declared affect how many times code runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for (int i = 0; i < n; i++) {
    int x = i * 2;
    // do something with x
}

int y = 0;
for (int i = 0; i < n; i++) {
    y += i;
}
    

This code shows two loops: one declares a variable inside the loop, the other outside.

Identify Repeating Operations

Look at the loops and variable declarations that repeat.

  • Primary operation: The for loops run n times each.
  • How many times: Each loop runs exactly n times.
  • Variable declarations: The variable inside the first loop is created and destroyed each time.
How Execution Grows With Input

As n grows, the loops run more times, but variable scope does not add extra loops.

Input Size (n)Approx. Operations
10About 20 loop steps (2 loops x 10 each)
100About 200 loop steps
1000About 2000 loop steps

Pattern observation: The total steps grow linearly with n, regardless of where variables are declared.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Declaring a variable inside a loop makes the code slower by adding extra loops."

[OK] Correct: Declaring a variable inside a loop does not add more loops; it only creates the variable each time, which is very fast and does not change the main time growth.

Interview Connect

Understanding how variable scope affects performance helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

"What if we moved the variable declared inside the loop to outside the loop? How would the time complexity change?"