0
0
C++programming~5 mins

Why variables are needed in C++ - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why variables are needed
O(n)
Understanding Time Complexity

We want to see how using variables affects the steps a program takes.

How does storing and reusing values change the work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int sum = 0;
for (int i = 0; i < n; i++) {
    int value = i * 2;
    sum += value;
}
return sum;
    

This code calculates the sum of double each number from 0 up to n-1 using a variable to store the doubled value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop runs and repeats the calculation and addition.
  • How many times: Exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

Each time n grows, the loop runs more times, doing more work.

Input Size (n)Approx. Operations
10About 10 calculations and additions
100About 100 calculations and additions
1000About 1000 calculations and additions

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 finish grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Using a variable inside the loop makes the program slower because it adds extra steps."

[OK] Correct: The variable just holds a value temporarily and does not add extra loops or repeated work; it helps keep the code clear without changing how many times the loop runs.

Interview Connect

Understanding how variables affect the steps in a program helps you explain your code clearly and shows you know how programs work efficiently.

Self-Check

"What if we removed the variable and calculated the value directly inside the addition? How would the time complexity change?"