If statement in C - Time & Space Complexity
We want to see how the time it takes to run an if statement changes as the input changes.
Does the if statement make the program slower when input grows?
Analyze the time complexity of the following code snippet.
int checkNumber(int n) {
if (n > 0) {
return 1;
} else {
return 0;
}
}
This code checks if a number is positive and returns 1 if true, otherwise 0.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if condition check.
- How many times: Exactly once per function call.
Checking the if condition takes the same time no matter what number we give.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The time stays the same even if the input number grows.
Time Complexity: O(1)
This means the if statement takes the same amount of time no matter how big the input is.
[X] Wrong: "If statements take longer when the input number is bigger."
[OK] Correct: The if condition is just one check and does not repeat or grow with input size.
Understanding that simple decisions like if statements run quickly helps you explain how your code behaves in real situations.
"What if we added a loop inside the if statement? How would the time complexity change?"