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

Array iteration with for and foreach 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 print each number in the array using a for loop.

C Sharp (C#)
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}
Drag options to blanks, or click blank then click option'
A<
B>=
C<=
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes an IndexOutOfRangeException.
Using > or >= will not enter the loop correctly.
2fill in blank
medium

Complete the code to print each word in the array using a foreach loop.

C Sharp (C#)
string[] words = {"apple", "banana", "cherry"};
foreach ([1] word in words)
{
    Console.WriteLine(word);
}
Drag options to blanks, or click blank then click option'
Achar
Bint
Cstring
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using int or char causes a type mismatch error.
Using bool is incorrect because the array does not contain boolean values.
3fill in blank
hard

Fix the error in the for loop condition to avoid runtime errors.

C Sharp (C#)
double[] values = {2.5, 3.6, 4.7};
for (int index = 0; index < values.Length; index++)
{
    Console.WriteLine(values[index]);
}
Drag options to blanks, or click blank then click option'
A<=
B<
C>
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= causes the loop to run one time too many.
Using > or >= will not enter the loop properly.
4fill in blank
hard

Fill both blanks to create a dictionary with word lengths for words longer than 3 characters.

C Sharp (C#)
string[] words = {"cat", "elephant", "dog", "giraffe"};
var lengths = new Dictionary<string, int>();
foreach (var word in words)
{
    if (word.Length > 3)
    {
        lengths[word] = word.Length;
    }
}
Drag options to blanks, or click blank then click option'
ALength
BCount
CLength()
DCount()
Attempts:
3 left
💡 Hint
Common Mistakes
Using Count or Count() causes errors because strings do not have these members.
Using Length() with parentheses causes a syntax error.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys and their lengths as values for words longer than 4 characters.

C Sharp (C#)
string[] words = {"tree", "mountain", "river", "sky"};
var result = new Dictionary<string, int>();
foreach (var word in words)
{
    if (word.Length > 4)
    {
        result[word.ToUpper()] = word.Length;
    }
}
Drag options to blanks, or click blank then click option'
ALength
CToUpper
DToLower
Attempts:
3 left
💡 Hint
Common Mistakes
Using Length() with parentheses causes errors.
Using ToLower() instead of ToUpper() changes the case incorrectly.