Array iteration with for and foreach in C Sharp (C#) - Time & Space 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?
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 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
ntimes wherenis the array length.
As the array gets bigger, the number of times we print grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows in a straight line with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows directly with the number of elements in the array.
[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.
Understanding how loops scale with input size is a key skill. It helps you write efficient code and explain your choices clearly during interviews.
"What if we nested one loop inside another to compare every element with every other? How would the time complexity change?"