Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Foreach loop over collections in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Foreach Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of foreach loop over array
What is the output of the following C# code?
C Sharp (C#)
string[] fruits = {"apple", "banana", "cherry"};
foreach (var fruit in fruits)
{
    Console.Write(fruit[0]);
}
Aabc
Bapplebananacherry
CSyntax error
Da b c
Attempts:
2 left
💡 Hint
Look at what character of each string is printed inside the loop.
❓ Predict Output
intermediate
2:00remaining
Foreach loop over Dictionary keys
What will be printed by this C# code?
C Sharp (C#)
var dict = new Dictionary<int, string> {{1, "one"}, {2, "two"}};
foreach (var key in dict.Keys)
{
    Console.Write(key + " ");
}
AKeyValuePair<int,string> KeyValuePair<int,string>
Bone two
CCompilation error
D1 2
Attempts:
2 left
💡 Hint
The loop iterates over the keys, not the values.
🔧 Debug
advanced
2:00remaining
Identify the runtime error in foreach loop
What error will this code cause when run?
C Sharp (C#)
List<int> numbers = null;
foreach (var num in numbers)
{
    Console.Write(num);
}
AInvalidOperationException
BNullReferenceException
CNo error, prints nothing
DSyntax error
Attempts:
2 left
💡 Hint
Consider what happens if you try to loop over a null list.
❓ Predict Output
advanced
2:00remaining
Foreach loop with modification inside loop
What is the output of this C# code?
C Sharp (C#)
var list = new List<int> {1, 2, 3};
foreach (var item in list)
{
    Console.Write(item);
    list.Add(item + 3);
    if (list.Count > 6) break;
}
A1234
B123456
CInvalidOperationException
D123
Attempts:
2 left
💡 Hint
Modifying a collection while iterating it causes an error.
🧠 Conceptual
expert
3:00remaining
Foreach loop behavior with custom collection
Given a custom collection implementing IEnumerable that yields numbers 1 to 3, what will this code print?
foreach (var x in customCollection)
{
    Console.Write(x);
}
C Sharp (C#)
using System.Collections;
using System.Collections.Generic;

public class CustomCollection : IEnumerable<int>
{
    public IEnumerator<int> GetEnumerator()
    {
        yield return 1;
        yield return 2;
        yield return 3;
    }
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

var customCollection = new CustomCollection();
foreach (var x in customCollection)
{
    Console.Write(x);
}
A123
B1 2 3
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
The custom collection yields numbers 1, 2, and 3 sequentially.

Practice

(1/5)
1. What does a foreach loop do in C#?
easy
A. It visits each item in a collection one by one.
B. It creates a new collection from scratch.
C. It only runs once regardless of collection size.
D. It deletes items from a collection while looping.

Solution

  1. Step 1: Understand the purpose of foreach

    The foreach loop is designed to go through each element in a collection without manual index handling.
  2. 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.
  3. Final Answer:

    It visits each item in a collection one by one. -> Option A
  4. Quick Check:

    foreach loops = visit items one by one [OK]
Hint: Foreach always processes every item in the collection [OK]
Common Mistakes:
  • Thinking foreach modifies the collection
  • Confusing foreach with creating collections
  • Assuming foreach runs only once
2. Which of the following is the correct syntax for a foreach loop over a list of strings named names?
easy
A. foreach (name string in names) { Console.WriteLine(name); }
B. foreach (string name in names) { Console.WriteLine(name); }
C. foreach string name in names { Console.WriteLine(name); }
D. foreach (string name : names) { Console.WriteLine(name); }

Solution

  1. Step 1: Recall correct foreach syntax

    The correct syntax uses parentheses with type and variable, then 'in' keyword before collection.
  2. 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.
  3. Final Answer:

    foreach (string name in names) { Console.WriteLine(name); } -> Option B
  4. Quick Check:

    foreach syntax = (type variable in collection) [OK]
Hint: Remember: foreach uses (type variable in collection) [OK]
Common Mistakes:
  • Omitting parentheses
  • Using ':' instead of 'in'
  • Swapping variable and type order
3. What will be the output of this code?
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
    Console.Write(fruit + " ");
}
medium
A. apple banana cherry
B. applebanana cherry
C. apple, banana, cherry
D. apple banana cherry

Solution

  1. Step 1: Understand the loop behavior

    The foreach loop prints each fruit followed by a space, all on the same line.
  2. Step 2: Analyze output format

    Since Console.Write (not WriteLine) is used, output is continuous with spaces between fruits.
  3. Final Answer:

    apple banana cherry -> Option A
  4. Quick Check:

    foreach prints items with space = apple banana cherry [OK]
Hint: Console.Write prints inline; spaces separate items [OK]
Common Mistakes:
  • Assuming Console.WriteLine adds spaces
  • Expecting commas between items
  • Thinking output is on separate lines
4. Identify the error in this code snippet:
List<int> numbers = new List<int> {1, 2, 3};
foreach (int num in numbers)
{
    numbers.Remove(num);
}
medium
A. Variable 'num' is not declared.
B. Missing semicolon after foreach statement.
C. Cannot modify collection while iterating with foreach.
D. List initialization syntax is incorrect.

Solution

  1. Step 1: Understand foreach restrictions

    Modifying a collection (like removing items) while using foreach causes runtime errors.
  2. Step 2: Check other options

    Semicolon is not needed after foreach header. Variable 'num' is declared. List initialization is correct.
  3. Final Answer:

    Cannot modify collection while iterating with foreach. -> Option C
  4. Quick Check:

    Modifying collection in foreach = error [OK]
Hint: Don't change collection inside foreach loop [OK]
Common Mistakes:
  • Trying to remove items inside foreach
  • Confusing foreach syntax errors
  • Ignoring runtime exceptions
5. Given a dictionary Dictionary<string, int> scores, how can you use a foreach loop to print all keys with values greater than 50?
hard
A. foreach (var pair in scores) { Console.WriteLine(pair.Value > 50); }
B. foreach (string key in scores.Values) { if (key > 50) Console.WriteLine(key); }
C. foreach (int value in scores.Keys) { if (value > 50) Console.WriteLine(value); }
D. foreach (var pair in scores) { if (pair.Value > 50) Console.WriteLine(pair.Key); }

Solution

  1. Step 1: Understand dictionary iteration

    Iterating a dictionary with foreach gives key-value pairs as 'var pair'.
  2. 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.
  3. 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.
  4. Final Answer:

    foreach (var pair in scores) { if (pair.Value > 50) Console.WriteLine(pair.Key); } -> Option D
  5. Quick Check:

    Use var pair and check Value > 50 [OK]
Hint: Use var pair to access key and value in dictionary [OK]
Common Mistakes:
  • Iterating keys as values or vice versa
  • Printing booleans instead of keys
  • Wrong variable types in foreach
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard