Else–if ladder in C - Time & Space 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?
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 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.
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) |
|---|---|
| 3 | 1 to 3 checks |
| 10 | 1 to 10 checks |
| 100 | 1 to 100 checks |
Pattern observation: The number of checks grows linearly with the number of conditions.
Time Complexity: O(n)
This means the time to find the right condition grows in a straight line as the number of conditions increases.
[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.
Understanding how else-if ladders scale helps you write efficient condition checks and shows you can think about how code runs as it grows.
"What if we replaced the else-if ladder with a switch statement? How would the time complexity change?"