0
0
C Sharp (C#)programming~5 mins

Return values and void methods in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Return values and void methods
O(n)
Understanding Time Complexity

Let's see how the time it takes to run a method changes depending on what the method does.

We want to know how the method's work grows as input changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

public int SumArray(int[] numbers)
{
    int sum = 0;
    for (int i = 0; i < numbers.Length; i++)
    {
        sum += numbers[i];
    }
    return sum;
}

public void PrintHello()
{
    Console.WriteLine("Hello!");
}

This code has two methods: one adds up all numbers in an array and returns the total, the other just prints a message and returns nothing.

Identify Repeating Operations

Look for loops or repeated steps.

  • Primary operation: The for-loop in SumArray that goes through each number.
  • How many times: It runs once for every item in the input array.
  • PrintHello method: No loops, just one print action.
How Execution Grows With Input

As the array gets bigger, the method does more work.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

Pattern observation: The work grows directly with the number of items. More items mean more additions.

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: "Since PrintHello doesn't return anything, it must take longer than SumArray."

[OK] Correct: PrintHello just does one action, so it takes the same time no matter what. The return type (void or int) doesn't affect how long it runs.

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you know how programs grow with input size.

Self-Check

What if we changed the SumArray method to call another method inside the loop? How would the time complexity change?