If statement execution flow in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to run an if statement changes as the input changes.
Specifically, we ask: does the if statement make the program slower when inputs grow?
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 and returns 1 or -1 accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if condition check.
- How many times: Exactly once per function call.
Whether the input number is small or large, the if statement runs just once.
| 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 how big the input is.
Time Complexity: O(1)
This means the if statement takes the same amount of time no matter the input size.
[X] Wrong: "If statements take longer when numbers are bigger because they compare values."
[OK] Correct: The if condition runs once and does not repeat, so size of the number does not affect time.
Understanding that simple if checks run in constant time helps you explain how decisions in code affect performance.
"What if we added a loop that runs n times inside the if block? How would the time complexity change?"