0
0
Cprogramming~5 mins

Why conditional logic is needed - Performance Analysis

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

We want to see how adding choices in code affects how long it 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.


#include <stdio.h>

void checkNumbers(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 == 0) {
            printf("%d is even\n", arr[i]);
        } else {
            printf("%d is odd\n", arr[i]);
        }
    }
}

This code goes through each number and prints if it is even or odd.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that checks each number once.
  • How many times: Exactly once per item in the array, so n times.
How Execution Grows With Input

As the list gets bigger, the program checks more numbers one by one.

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 with the input size.

Common Mistake

[X] Wrong: "Adding an if-else inside the loop doubles the time complexity."

[OK] Correct: The if-else only adds a small fixed check each time, so it does not change how the total time grows 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?"