Complete the code to loop through each number in the array and print it.
int[] numbers = {1, 2, 3, 4, 5};
foreach ([1] number in numbers)
{
Console.WriteLine(number);
}string or double instead of int causes errors.The foreach loop requires the type of the elements in the collection. Since numbers is an array of int, we use int before the variable name.
Complete the code to loop through each character in the string and print it.
string word = "hello"; foreach ([1] ch in word) { Console.WriteLine(ch); }
string instead of char causes errors.int which is not the correct type for characters.A string is a collection of characters. The foreach loop variable should be of type char to represent each character.
Fix the error in the foreach loop to correctly iterate over the list of strings.
List<string> fruits = new List<string> {"apple", "banana", "cherry"};
foreach (string [1] in fruits)
{
Console.WriteLine([1]);
}fruits as the loop variable.The loop variable should be a single element from the collection. Using fruit is correct. Using fruits (the collection name) causes confusion and errors.
Fill both blanks to create a foreach loop that prints each key and value from the dictionary.
Dictionary<string, int> ages = new Dictionary<string, int> { {"Alice", 30}, {"Bob", 25} };
foreach (KeyValuePair<[1], [2]> entry in ages)
{
Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
}The dictionary has keys of type string and values of type int. The KeyValuePair generic requires these types in order.
Fill all three blanks to create a foreach loop that prints each character and its index from the string.
string text = "code"; int index = 0; foreach ([1] ch in text) { Console.WriteLine($"Character {index}: {ch}"); index [2] [3]; }
int as the loop variable type instead of char.++ instead of += (both work but only one is in options).The loop variable is a char because we iterate over characters. To increase the index by one each time, use index += 1;.