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

Why loops are needed in C Sharp (C#) - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why loops are needed
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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

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

Explain the growth pattern intuitively.

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

Pattern observation: As the input size grows, the number of additions grows at the same rate.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of items we process.

Common Mistake

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

Interview Connect

Understanding how loops affect time helps you explain your code clearly and shows you know how programs handle bigger data.

Self-Check

"What if we added a nested loop inside this loop? How would the time complexity change?"