Top-level statements in modern C# - Time & Space 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?
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.
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.
As n gets bigger, the loop runs more times, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the running time grows in a straight line with the size of the input n.
[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.
Understanding how loops inside top-level statements affect time helps you explain code efficiency clearly and confidently.
What if we replaced the for-loop with two nested for-loops each running n times? How would the time complexity change?