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

Top-level statements in modern C# - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Top-level statements in modern C#
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a program with top-level statements changes as the program grows.

Specifically, how does adding more code or operations affect the running time?

Scenario Under Consideration

Analyze the time complexity of the following top-level statements code.


int sum = 0;
for (int i = 0; i < n; i++)
{
    sum += i;
}
Console.WriteLine(sum);
    

This code sums numbers from 0 up to n-1 and prints the result using top-level statements.

Identify Repeating Operations

Look for loops or repeated actions.

  • Primary operation: The for-loop that adds numbers.
  • How many times: It runs once for each number from 0 to n-1, so n times.
How Execution Grows With Input

As n gets bigger, the loop runs more times, so the work grows steadily.

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

Pattern observation: The number of operations grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the running time grows in a straight line with the size of the input n.

Common Mistake

[X] Wrong: "Top-level statements make the program run instantly regardless of input size."

[OK] Correct: Top-level statements just let you write code without extra wrapping, but the loop inside still runs n times, so time depends on n.

Interview Connect

Understanding how loops inside top-level statements affect time helps you explain code efficiency clearly and confidently.

Self-Check

What if we replaced the for-loop with two nested for-loops each running n times? How would the time complexity change?