Challenge - 5 Problems
Foreach Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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]);
}Attempts:
2 left
💡 Hint
Look at what character of each string is printed inside the loop.
✗ Incorrect
The loop prints the first character of each fruit string without spaces, so output is 'abc'.
❓ Predict Output
intermediate2: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 + " "); }
Attempts:
2 left
💡 Hint
The loop iterates over the keys, not the values.
✗ Incorrect
dict.Keys returns the keys 1 and 2, which are printed with a space.
🔧 Debug
advanced2: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); }
Attempts:
2 left
💡 Hint
Consider what happens if you try to loop over a null list.
✗ Incorrect
The variable 'numbers' is null, so foreach throws NullReferenceException at runtime.
❓ Predict Output
advanced2: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; }
Attempts:
2 left
💡 Hint
Modifying a collection while iterating it causes an error.
✗ Incorrect
Adding items to the list during foreach causes InvalidOperationException at runtime.
🧠 Conceptual
expert3: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); }
Attempts:
2 left
💡 Hint
The custom collection yields numbers 1, 2, and 3 sequentially.
✗ Incorrect
The foreach prints each yielded number without spaces, so output is '123'.