Foreach loop over collections in C Sharp (C#) - Time & Space Complexity
When we use a foreach loop to go through a collection, we want to know how the time it takes changes as the collection grows.
We ask: How does the number of steps grow when the collection gets bigger?
Analyze the time complexity of the following code snippet.
List numbers = new List {1, 2, 3, 4, 5};
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
Console.WriteLine(sum);
This code adds up all numbers in a list using a foreach loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The foreach loop that visits each item in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the loop runs more times, one for each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The number of steps grows directly with the size of the list.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "The foreach loop runs in constant time no matter how big the list is."
[OK] Correct: The loop must visit each item, so if the list doubles, the loop runs twice as many times.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave with bigger data.
"What if we replaced the foreach loop with two nested foreach loops over the same list? How would the time complexity change?"
Practice
foreach loop do in C#?Solution
Step 1: Understand the purpose of foreach
The foreach loop is designed to go through each element in a collection without manual index handling.Step 2: Compare options to foreach behavior
Only It visits each item in a collection one by one. correctly describes visiting each item one by one. Other options describe actions foreach does not perform.Final Answer:
It visits each item in a collection one by one. -> Option AQuick Check:
foreach loops = visit items one by one [OK]
- Thinking foreach modifies the collection
- Confusing foreach with creating collections
- Assuming foreach runs only once
foreach loop over a list of strings named names?Solution
Step 1: Recall correct foreach syntax
The correct syntax uses parentheses with type and variable, then 'in' keyword before collection.Step 2: Check each option
foreach (string name in names) { Console.WriteLine(name); } matches correct syntax. foreach string name in names { Console.WriteLine(name); } misses parentheses. foreach (name string in names) { Console.WriteLine(name); } swaps type and variable. foreach (string name : names) { Console.WriteLine(name); } uses ':' which is invalid in C# foreach.Final Answer:
foreach (string name in names) { Console.WriteLine(name); } -> Option BQuick Check:
foreach syntax = (type variable in collection) [OK]
- Omitting parentheses
- Using ':' instead of 'in'
- Swapping variable and type order
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
Console.Write(fruit + " ");
}Solution
Step 1: Understand the loop behavior
The foreach loop prints each fruit followed by a space, all on the same line.Step 2: Analyze output format
Since Console.Write (not WriteLine) is used, output is continuous with spaces between fruits.Final Answer:
apple banana cherry -> Option AQuick Check:
foreach prints items with space = apple banana cherry [OK]
- Assuming Console.WriteLine adds spaces
- Expecting commas between items
- Thinking output is on separate lines
List<int> numbers = new List<int> {1, 2, 3};
foreach (int num in numbers)
{
numbers.Remove(num);
}Solution
Step 1: Understand foreach restrictions
Modifying a collection (like removing items) while using foreach causes runtime errors.Step 2: Check other options
Semicolon is not needed after foreach header. Variable 'num' is declared. List initialization is correct.Final Answer:
Cannot modify collection while iterating with foreach. -> Option CQuick Check:
Modifying collection in foreach = error [OK]
- Trying to remove items inside foreach
- Confusing foreach syntax errors
- Ignoring runtime exceptions
Dictionary<string, int> scores, how can you use a foreach loop to print all keys with values greater than 50?Solution
Step 1: Understand dictionary iteration
Iterating a dictionary with foreach gives key-value pairs as 'var pair'.Step 2: Filter and print keys with values > 50
Check pair.Value > 50, then print pair.Key. foreach (var pair in scores) { if (pair.Value > 50) Console.WriteLine(pair.Key); } does this correctly.Step 3: Analyze incorrect options
foreach (string key in scores.Values) { if (key > 50) Console.WriteLine(key); } tries to iterate values as strings (wrong). foreach (int value in scores.Keys) { if (value > 50) Console.WriteLine(value); } iterates keys as ints (wrong). foreach (var pair in scores) { Console.WriteLine(pair.Value > 50); } prints booleans, not keys.Final Answer:
foreach (var pair in scores) { if (pair.Value > 50) Console.WriteLine(pair.Key); } -> Option DQuick Check:
Use var pair and check Value > 50 [OK]
- Iterating keys as values or vice versa
- Printing booleans instead of keys
- Wrong variable types in foreach
Ready to prove it?
Pass the test and this pattern moves unknown
