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

Foreach loop over collections in C Sharp (C#) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to loop through each number in the array and print it.

C Sharp (C#)
int[] numbers = {1, 2, 3, 4, 5};
foreach ([1] number in numbers)
{
    Console.WriteLine(number);
}
Drag options to blanks, or click blank then click option'
Adouble
Bstring
Cvar
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using string or double instead of int causes errors.
Leaving out the type before the variable name.
2fill in blank
medium

Complete the code to loop through each character in the string and print it.

C Sharp (C#)
string word = "hello";
foreach ([1] ch in word)
{
    Console.WriteLine(ch);
}
Drag options to blanks, or click blank then click option'
Achar
Bstring
Cint
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Using string instead of char causes errors.
Using int which is not the correct type for characters.
3fill in blank
hard

Fix the error in the foreach loop to correctly iterate over the list of strings.

C Sharp (C#)
List<string> fruits = new List<string> {"apple", "banana", "cherry"};
foreach (string [1] in fruits)
{
    Console.WriteLine([1]);
}
Drag options to blanks, or click blank then click option'
Afruits
Bfruit
Citem
Df
Attempts:
3 left
💡 Hint
Common Mistakes
Using the collection name fruits as the loop variable.
Using a variable name that is not descriptive.
4fill in blank
hard

Fill both blanks to create a foreach loop that prints each key and value from the dictionary.

C Sharp (C#)
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.");
}
Drag options to blanks, or click blank then click option'
Astring
Bint
Cdouble
Dchar
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the key and value types.
Using types not matching the dictionary declaration.
5fill in blank
hard

Fill all three blanks to create a foreach loop that prints each character and its index from the string.

C Sharp (C#)
string text = "code";
int index = 0;
foreach ([1] ch in text)
{
    Console.WriteLine($"Character {index}: {ch}");
    index [2] [3];
}
Drag options to blanks, or click blank then click option'
Achar
B+=
C1
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using int as the loop variable type instead of char.
Using ++ instead of += (both work but only one is in options).
Forgetting to increment the index.