0
0
C Sharp (C#)programming~5 mins

Nested conditional execution in C Sharp (C#) - Time & Space Complexity

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

Let's see how nested conditions affect the time it takes for a program to run.

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

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

This code checks if a number is positive, then if it is even or odd, and returns a value accordingly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated steps here, only simple checks.
  • How many times: Each condition runs once per function call.
How Execution Grows With Input

Since the code only 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: "More nested conditions always make the program slower as input grows."

[OK] Correct: Nested conditions only add fixed checks, not repeated steps, so time stays constant.

Interview Connect

Understanding how 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 inside the nested conditions? How would the time complexity change?"