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

If-else execution flow in C Sharp (C#) - Time & Space Complexity

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

We want to understand how the time taken by an if-else decision changes as the input size changes.

Specifically, does choosing one path or another affect how long the program runs?

Scenario Under Consideration

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 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

Whether the input is small or large, the program only does one check.

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

Pattern observation: The number of operations stays the same no matter the input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run this code does not grow with input size; it stays constant.

Common Mistake

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

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

Interview Connect

Understanding that simple decisions take constant time helps you explain how your code behaves clearly and confidently.

Self-Check

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