0
0
Cprogramming~5 mins

Else–if ladder in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Else-if ladder
O(n)
Understanding Time Complexity

We want to understand how the time taken by an else-if ladder changes as the input changes.

Specifically, how many checks happen before the program finds the right condition?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int checkNumber(int num) {
    if (num == 1) {
        return 10;
    } else if (num == 2) {
        return 20;
    } else if (num == 3) {
        return 30;
    } else {
        return 40;
    }
}
    

This code checks a number against several conditions one by one until it finds a match.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking conditions one after another in the else-if ladder.
  • How many times: Up to the number of conditions until a match is found.
How Execution Grows With Input

As the input number changes, the program checks conditions in order until it finds a match or reaches the end.

Input Size (number of conditions)Approx. Operations (checks)
31 to 3 checks
101 to 10 checks
1001 to 100 checks

Pattern observation: The number of checks grows linearly with the number of conditions.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the right condition grows in a straight line as the number of conditions increases.

Common Mistake

[X] Wrong: "The else-if ladder always takes the same time no matter how many conditions there are."

[OK] Correct: The program checks conditions one by one, so more conditions mean more checks and more time in the worst case.

Interview Connect

Understanding how else-if ladders scale helps you write efficient condition checks and shows you can think about how code runs as it grows.

Self-Check

"What if we replaced the else-if ladder with a switch statement? How would the time complexity change?"