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

Method declaration and calling in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method declaration and calling
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

As n grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
1010 times printing
100100 times printing
10001000 times printing

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

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line as the input number n grows.

Common Mistake

[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.

Interview Connect

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

Self-Check

"What if the method called itself inside (recursion) instead of using a loop? How would the time complexity change?"