Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print each character of the string text using a for loop.
DSA C++
std::string text = "hello"; for (int i = 0; i < text.length(); i++) { std::cout << text[1] << ' '; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets for indexing.
Using curly braces or angle brackets which are invalid for indexing.
✗ Incorrect
In C++, to access a character at a specific position in a string, use square brackets with the index inside, like text[i].
2fill in blank
mediumComplete the code to print the last character of the string word.
DSA C++
std::string word = "world"; char lastChar = word[1]; std::cout << lastChar << std::endl;
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.length() as index which is out of range.
Using index 0 which is the first character, not 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 str using a range-based for loop.
DSA C++
std::string str = "code"; for (char c [1] str) { std::cout << c << ' '; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'in' or 'of' which are not valid in C++ range-based for loops.
Using 'from' which is invalid syntax.
✗ Incorrect
In C++, the range-based for loop uses a colon ':' to separate the variable and the container.
4fill in blank
hardFill both blanks to create a map of characters to their counts from the string input.
DSA C++
std::string input = "banana"; std::map<char, int> counts; for (char [1] : input) { counts[[2]]++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in loop and map access causing errors.
Using reserved words like 'char' as variable names.
✗ Incorrect
The loop variable is named 'ch' and the map key accessed is also 'ch' to count characters.
5fill in blank
hardFill all three blanks to create a vector of characters from text that are vowels.
DSA C++
std::string text = "education"; std::vector<char> vowels; for (char [1] : text) { if ([2] == 'a' || [3] == 'e' || [3] == 'i' || [3] == 'o' || [3] == 'u') { vowels.push_back([1]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in the condition and push_back causing errors.
Using undefined variables in the if condition.
✗ Incorrect
The loop variable 'ch' is used consistently to check vowels and to add to the vector.
