Using return codes - Time & Space Complexity
When using return codes in C, it's important to see how the program's steps grow as input changes.
We want to know how the number of operations changes when the input size grows.
Analyze the time complexity of the following code snippet.
int processArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
if (arr[i] < 0) {
return -1; // error code for negative value
}
}
return 0; // success code
}
This code checks an array for negative values and returns a code indicating success or error.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop through the array elements one by one.
- How many times: Up to n times, where n is the array size.
As the array size grows, the number of checks grows roughly the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The work grows directly with the input size, one check per item.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items to check.
[X] Wrong: "The return statement makes the loop always run only once."
[OK] Correct: The loop stops early only if a negative value is found; otherwise, it checks all items.
Understanding how return codes affect loop execution helps you explain program efficiency clearly and confidently.
"What if the function returned a code only after checking every element, without early return? How would the time complexity change?"