Why conditional flow control is needed in C Sharp (C#) - Performance Analysis
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?
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 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.
As the list gets bigger, the program checks each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input gets bigger.
[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.
Understanding how conditions inside loops affect time helps you explain your code clearly and shows you know how programs scale.
"What if we added a nested loop inside the if-condition? How would the time complexity change?"