0
0
C++programming~5 mins

Nested conditional statements in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested conditional statements
O(1)
Understanding Time Complexity

Let's see how nested conditional statements affect how long a program takes to run.

We want to know if adding more conditions makes the program slower as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int checkNumber(int x) {
    if (x > 0) {
        if (x % 2 == 0) {
            return 1;
        } else {
            return 2;
        }
    } else {
        return 3;
    }
}
    

This code checks if a number is positive and then if it is even or odd, returning different values.

Identify Repeating Operations

Look for loops or repeated steps that happen many times.

  • Primary operation: The code only uses simple if-else checks, no loops or recursion.
  • How many times: Each condition runs once per function call.
How Execution Grows With Input

Since the code just checks conditions once, the time does not grow with input size.

Input Size (n)Approx. Operations
103 checks
1003 checks
10003 checks

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

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same short time no matter how big the input number is.

Common Mistake

[X] Wrong: "Nested ifs make the program slower as input grows because they are inside each other."

[OK] Correct: Nested conditions just check one after another once; they don't repeat many times, so time stays constant.

Interview Connect

Understanding how simple conditions affect time helps you explain your code clearly and shows you know what really slows programs down.

Self-Check

"What if we added a loop around these nested conditions? How would the time complexity change?"