0
0
C++programming~5 mins

Why loops are needed in C++ - Performance Analysis

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

Loops help us repeat actions many times without writing the same code again and again.

We want to know how the time to run the code changes when we repeat tasks more times.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

This code adds numbers from 0 up to n-1 and returns the total sum.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding a number to sum inside the loop.
  • How many times: The loop runs n times, once for each number from 0 to n-1.
How Execution Grows With Input

Each time n gets bigger, the loop runs more times, so the work grows in a straight line.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: When n doubles, the work doubles too.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of times we repeat the loop.

Common Mistake

[X] Wrong: "The loop runs only once, so it takes constant time."

[OK] Correct: The loop runs n times, so the time depends on n, not just once.

Interview Connect

Understanding how loops affect time helps you explain how your code handles bigger tasks clearly and confidently.

Self-Check

"What if we added a second nested loop inside the first? How would the time complexity change?"