Why conditional logic is needed in C++ - Performance Analysis
Conditional logic helps programs decide what to do next based on different situations.
We want to see how adding conditions affects how long a program takes to run.
Analyze the time complexity of the following code snippet.
int process(int n) {
if (n > 0) {
for (int i = 0; i < n; i++) {
// do something simple
}
} else {
// do nothing
}
return 0;
}
This code runs a loop only if the input number is positive; otherwise, it skips the loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from 0 to n-1.
- How many times: Up to n times, but only if n is positive.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop steps |
| 100 | About 100 loop steps |
| 1000 | About 1000 loop steps |
Pattern observation: When n is positive, the work grows directly with n; if n is zero or negative, no loop runs.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size when the condition allows the loop.
[X] Wrong: "The condition makes the program always run in constant time because it sometimes skips the loop."
[OK] Correct: The condition only skips the loop for some inputs; when the loop runs, time grows with n, so overall time depends on input size.
Understanding how conditions affect time helps you explain program behavior clearly and shows you can think about efficiency in real situations.
"What if the loop ran twice inside the condition? How would the time complexity change?"