0
0
Cprogramming~5 mins

Use cases - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Use cases
O(n)
Understanding Time Complexity

When we look at use cases in programming, we want to know how the time a program takes changes as the input grows.

We ask: How does the program's work increase when we give it more data?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

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

int main() {
    printNumbers(5);
    return 0;
}
    

This code prints numbers from 0 up to n-1, showing a simple use case of a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that prints each number.
  • How many times: It runs exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

As n grows, the number of print operations grows the same way.

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

Pattern observation: The work grows directly with the input size; double the input, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the size of the input.

Common Mistake

[X] Wrong: "The loop runs faster because it just prints numbers quickly."

[OK] Correct: The speed of printing doesn't change the fact that the loop runs once per input item, so time still grows with n.

Interview Connect

Understanding how simple loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.

Self-Check

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