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

Array iteration with for and foreach in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array iteration with for and foreach
O(n)
Understanding Time Complexity

When we loop through an array, the time it takes depends on how many items are inside. We want to understand how the time grows as the array gets bigger.

How does the choice between for and foreach affect the time it takes to go through all items?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int[] numbers = new int[n];

// Using for loop
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

// Using foreach loop
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

This code prints every number in the array using two different loops: a for loop and a foreach loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing and printing each element in the array.
  • How many times: Exactly once for each element, so n times where n is the array length.
How Execution Grows With Input

As the array gets bigger, the number of times we print grows directly with the number of items.

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

Pattern observation: The work grows in a straight line with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of elements in the array.

Common Mistake

[X] Wrong: "foreach is slower than for because it looks more complex."

[OK] Correct: Both loops visit each item once, so they take about the same time. The difference is usually very small and depends on the compiler and runtime, not the loop type.

Interview Connect

Understanding how loops scale with input size is a key skill. It helps you write efficient code and explain your choices clearly during interviews.

Self-Check

"What if we nested one loop inside another to compare every element with every other? How would the time complexity change?"