Nested conditional execution in C Sharp (C#) - Time & Space Complexity
Let's see how nested conditions affect the time it takes for a program to run.
We want to know if adding more conditions inside each other makes the program slower as input grows.
Analyze the time complexity of the following code snippet.
int CheckNumber(int n) {
if (n > 0) {
if (n % 2 == 0) {
return 1;
} else {
return 2;
}
} else {
return 3;
}
}
This code checks if a number is positive, then if it is even or odd, and returns a value accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: There are no loops or repeated steps here, only simple checks.
- How many times: Each condition runs once per function call.
Since the code only checks conditions once, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 checks |
| 100 | 3 checks |
| 1000 | 3 checks |
Pattern observation: The number of steps stays the same no matter how big the input is.
Time Complexity: O(1)
This means the program takes the same short time no matter how big the input number is.
[X] Wrong: "More nested conditions always make the program slower as input grows."
[OK] Correct: Nested conditions only add fixed checks, not repeated steps, so time stays constant.
Understanding how conditions affect time helps you explain your code clearly and shows you know what really slows programs down.
"What if we added a loop inside the nested conditions? How would the time complexity change?"