If–else statement in C++ - Time & Space Complexity
We want to see how the time it takes to run an if-else statement changes as the input changes.
Specifically, does choosing one path or the other 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.
The program always does one check no matter what the input number is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same even if the input changes.
Time Complexity: O(1)
This means the time to run the code does not grow with input size; it stays constant.
[X] Wrong: "If-else takes longer for bigger numbers because it has to check more conditions."
[OK] Correct: The if-else only checks one condition once, no matter how big the number is.
Understanding that simple decisions like if-else run in constant time helps you explain how your code behaves clearly and confidently.
"What if we added a loop inside the if block that runs n times? How would the time complexity change?"