If-else execution flow in C Sharp (C#) - Time & Space Complexity
We want to understand how the time taken by an if-else decision changes as the input size changes.
Specifically, does choosing one path or another affect how long the program runs?
Analyze the time complexity of the following code snippet.
int CheckNumber(int n)
{
if (n > 0)
{
return 1;
}
else
{
return -1;
}
}
This code checks if a number is positive or not and returns a value accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if-else check.
- How many times: Exactly once per function call.
Whether the input is small or large, the program only does one check.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the time to run this code does not grow with input size; it stays constant.
[X] Wrong: "If the input number is very large, the if-else will take longer to decide."
[OK] Correct: The if-else only checks one condition once, so size or value of the input does not affect the time.
Understanding that simple decisions take constant time helps you explain how your code behaves clearly and confidently.
"What if we added a loop that runs n times inside the if or else block? How would the time complexity change?"