0
0
Cprogramming~5 mins

Return values in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Return values
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the loop runs more times, so the work grows too.

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

Pattern observation: The number of steps grows directly with n, so doubling n doubles the work.

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: "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.

Interview Connect

Understanding how return values fit with loops helps you explain how functions behave in real code.

Self-Check

"What if we changed the loop to run only half of n? How would the time complexity change?"