0
0
Cprogramming~5 mins

Loop execution flow - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Loop execution flow
O(n)
Understanding Time Complexity

Loops are a basic way to repeat actions in code. Understanding how many times a loop runs helps us see how long a program might take.

We want to know how the work grows as the loop runs more times.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

This code prints numbers from 0 up to n-1, repeating the print action n times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The print statement inside the loop.
  • How many times: Exactly n times, once for each loop cycle.
How Execution Grows With Input

As n gets bigger, the number of print actions grows the same way.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the size of n.

Common Mistake

[X] Wrong: "The loop runs faster as n gets bigger because computers are fast."

[OK] Correct: Even though computers are fast, the loop still does more work when n is bigger, so it takes more time overall.

Interview Connect

Knowing how loops affect time helps you explain your code clearly and shows you understand how programs grow with input size.

Self-Check

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