Return values in C - Time & Space Complexity
Let's see how the time it takes to run code with return values changes as input grows.
We want to know how the program's steps increase when using return statements.
Analyze the time complexity of the following code snippet.
int sum(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i;
}
return total;
}
This code adds numbers from 1 to n and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop adding numbers one by one.
- How many times: It runs exactly n times, once for each number.
As n grows, the loop runs more times, so the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The return statement makes the function run faster or slower depending on the value returned."
[OK] Correct: The return just sends back the result after the loop finishes; it does not change how many steps the loop takes.
Understanding how return values fit with loops helps you explain how functions behave in real code.
"What if we changed the loop to run only half of n? How would the time complexity change?"