Improving code readability - Time & Space 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?
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 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.
As the array gets bigger, the number of additions grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the size of the input.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[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.
Understanding how code changes affect time helps you write clear and efficient programs, a skill valued in real projects and interviews.
"What if we added a nested loop inside the for-loop to compare each element with every other? How would the time complexity change?"