Else-if ladder execution in C Sharp (C#) - Time & Space Complexity
We want to understand how the time taken by an else-if ladder changes as the number of conditions grows.
Specifically, how many checks happen before the program finds the right condition?
Analyze the time complexity of the following code snippet.
int value = 7;
if (value == 1) {
Console.WriteLine("One");
} else if (value == 2) {
Console.WriteLine("Two");
} else if (value == 3) {
Console.WriteLine("Three");
} else if (value == 7) {
Console.WriteLine("Seven");
} else {
Console.WriteLine("Other");
}
This code checks several conditions one by one until it finds a match or reaches the end.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each condition in the else-if ladder.
- How many times: Up to the number of conditions, one by one until a match is found.
As the number of conditions increases, the program may check more conditions before stopping.
| Number of Conditions (n) | Approx. Checks Before Match |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of conditions.
Time Complexity: O(n)
This means the time to find the right condition grows linearly with how many conditions there are.
[X] Wrong: "The else-if ladder always runs in constant time because it stops as soon as it finds a match."
[OK] Correct: Sometimes the match is near the end or missing, so the program checks many conditions, making time grow with the number of conditions.
Understanding how else-if ladders scale helps you explain decision-making code clearly and shows you can think about efficiency in everyday programming.
"What if we replaced the else-if ladder with a dictionary lookup? How would the time complexity change?"