Why loops are needed in C Sharp (C#) - Performance Analysis
Loops help us repeat actions many times without writing the same code again and again.
We want to see how the time to run code changes when we use loops with bigger inputs.
Analyze the time complexity of the following code snippet.
int sum = 0;
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
{
sum += numbers[i];
}
Console.WriteLine(sum);
This code adds up all numbers in an array of size n using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to sum inside the loop.
- How many times: The loop runs once for each item in the array, so n times.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: As the input size grows, the number of additions grows at the same rate.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items we process.
[X] Wrong: "The loop runs only once no matter how big the input is."
[OK] Correct: The loop actually runs once for each item, so bigger inputs mean more work and more time.
Understanding how loops affect time helps you explain your code clearly and shows you know how programs handle bigger data.
"What if we added a nested loop inside this loop? How would the time complexity change?"