Method declaration and calling in C Sharp (C#) - Time & Space Complexity
When we declare and call a method, it is important to know how the time it takes grows as we use it more.
We want to find out how the number of steps changes when the method is called.
Analyze the time complexity of the following code snippet.
public void PrintNumbers(int n)
{
for (int i = 0; i < n; i++)
{
Console.WriteLine(i);
}
}
PrintNumbers(5);
This code defines a method that prints numbers from 0 up to n-1, then calls it with 5.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from 0 to n-1.
- How many times: It runs exactly n times, once for each number.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times printing |
| 100 | 100 times printing |
| 1000 | 1000 times printing |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time it takes grows in a straight line as the input number n grows.
[X] Wrong: "Calling a method once always takes the same time, no matter what the input is."
[OK] Correct: The method's time depends on what it does inside. If it loops n times, bigger n means more time.
Understanding how method calls affect time helps you explain your code clearly and shows you know how programs grow with input size.
"What if the method called itself inside (recursion) instead of using a loop? How would the time complexity change?"