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

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

Choose your learning style9 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.