0
0
Cprogramming~5 mins

If–else statement in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If-else statement
O(1)
Understanding Time Complexity

We want to see how the time to run an if-else statement changes as the input changes.

Does the program take longer if the input is bigger?

Scenario Under Consideration

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 or 0 accordingly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single if-else check.
  • How many times: Exactly once per function call.
How Execution Grows With Input

The time to run this code does not change with the size of the input number.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: The number of operations stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the if-else statement stays constant, no matter the input size.

Common Mistake

[X] Wrong: "If the input number is bigger, the if-else will take longer to decide."

[OK] Correct: The if-else only checks the condition once, so the input size does not affect the time.

Interview Connect

Understanding that simple if-else checks run in constant time helps you explain how decisions in code affect performance.

Self-Check

"What if we added a loop inside the else block that runs n times? How would the time complexity change?"