0
0
Cprogramming~5 mins

Improving code readability - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Improving code readability
O(n)
Understanding Time Complexity

When we improve code readability, we want to make the code easier to understand and maintain.

But how does this affect how long the program takes to run?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

int sumArray(int arr[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum;
}

int main() {
    int data[] = {1, 2, 3, 4, 5};
    int result = sumArray(data, 5);
    printf("Sum: %d\n", result);
    return 0;
}
    

This code adds all numbers in an array and prints the total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that adds each element of the array.
  • How many times: It runs once for each element in the array, so n times.
How Execution Grows With Input

As the array gets bigger, the number of additions grows in the same way.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the size of the input.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "Making code more readable will always slow it down."

[OK] Correct: Improving readability usually does not add extra loops or heavy work, so it does not change how long the program takes to run.

Interview Connect

Understanding how code changes affect time helps you write clear and efficient programs, a skill valued in real projects and interviews.

Self-Check

"What if we added a nested loop inside the for-loop to compare each element with every other? How would the time complexity change?"