What is C# - Complexity Analysis
When learning about C#, it helps to understand how the time your programs take to run can change as they get bigger or handle more data.
We want to see how the work done by C# programs grows when the input grows.
Analyze the time complexity of the following code snippet.
using System;
class Program {
static void Main() {
int n = 5;
for (int i = 0; i < n; i++) {
Console.WriteLine(i);
}
}
}
This code prints numbers from 0 up to n-1 using a simple loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints numbers.
- How many times: It runs once for each number from 0 to n-1, so n times.
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; double n means double work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the input.
[X] Wrong: "The loop runs the same time no matter how big n is."
[OK] Correct: Actually, the loop runs once for each number up to n, so bigger n means more work.
Understanding how loops affect time helps you explain how your C# code will behave with bigger data, a skill useful in many programming tasks.
"What if we changed the for-loop to a nested loop running n times inside another n times? How would the time complexity change?"