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

Why conditional flow control is needed in C Sharp (C#) - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why conditional flow control is needed
O(n)
Understanding Time Complexity

We want to see how adding conditions affects how long a program takes to run.

Does checking conditions slow down the program as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int SumPositiveNumbers(int[] numbers)
{
    int sum = 0;
    foreach (int num in numbers)
    {
        if (num > 0)
            sum += num;
    }
    return sum;
}
    

This code adds up only the positive numbers from an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the array.
  • How many times: Once for every number in the input array.
How Execution Grows With Input

As the list gets bigger, the program checks each number once.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input gets bigger.

Common Mistake

[X] Wrong: "Adding an if-condition inside a loop makes the program slower by a lot."

[OK] Correct: The condition only adds a small check each time, so the overall time still grows linearly with input size.

Interview Connect

Understanding how conditions inside loops affect time helps you explain your code clearly and shows you know how programs scale.

Self-Check

"What if we added a nested loop inside the if-condition? How would the time complexity change?"