Return values and void methods in C Sharp (C#) - Time & Space 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.
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.
Look for loops or repeated steps.
- Primary operation: The for-loop in
SumArraythat 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.
As the array gets bigger, the method does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items. More items mean more additions.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[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.
Understanding how loops affect time helps you explain your code clearly and shows you know how programs grow with input size.
What if we changed the SumArray method to call another method inside the loop? How would the time complexity change?