Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print each character of the string word using a for loop.
DSA C#
string word = "hello"; for (int i = 0; i < word.Length; i++) { Console.WriteLine(word[1]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets to access characters.
Using curly braces or angle brackets which are invalid here.
✗ Incorrect
In C#, strings can be accessed like arrays using square brackets with the index inside, e.g., word[i].
2fill in blank
mediumComplete the code to print the last character of the string text.
DSA C#
string text = "world"; char lastChar = text[1]; Console.WriteLine(lastChar);
Attempts:
3 left
💡 Hint
Common Mistakes
Using Length instead of Length - 1 causes an error.
Using index 0 gives the first character, not the last.
✗ Incorrect
The last character is at index Length - 1 because indexing starts at 0.
3fill in blank
hardFix the error in the code to correctly print each character of input using a foreach loop.
DSA C#
string input = "code"; foreach (char c [1] input) { Console.WriteLine(c); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'of' which is used in some other languages but not C#.
Using 'on' or 'at' which are invalid here.
✗ Incorrect
In C#, the correct keyword for iterating over elements in a collection is 'in'.
4fill in blank
hardComplete the code to create a dictionary that maps each word to its length for words longer than 3 characters.
DSA C#
string[] words = {"apple", "bat", "carrot", "dog"};
var lengths = words.ToDictionary(word => word, word => word.Length)[1](word => word.Key.Length > 3);
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to modify the word with ToUpper or ToLower when not needed.
Not using Where to filter the words.
✗ Incorrect
We keep the word as is (empty string) for the key and use Where to filter words longer than 3 characters.
5fill in blank
hardFill all three blanks to create a dictionary with uppercase words as keys and their lengths as values, only for words with length greater than 3.
DSA C#
string[] words = {"tree", "cat", "house", "dog"};
var result = words.Where(word => word.Length [1] 3)
.ToDictionary(word => word[2], word => word[3]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the filter.
Not converting keys to uppercase.
Using word.Length as key instead of value.
✗ Incorrect
We filter words with length > 3, convert keys to uppercase, and values are the length of the word.
