Challenge - 5 Problems
String Traversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of character access in a loop
What is the output of the following C++ code snippet?
DSA C++
std::string s = "hello"; for (int i = 0; i < s.size(); ++i) { std::cout << s[i] << "-"; }
Attempts:
2 left
💡 Hint
Remember that s[i] accesses one character at a time and the loop prints a dash after each character.
✗ Incorrect
The loop prints each character followed by a dash. Since the loop runs from 0 to s.size()-1, it prints all characters with a dash after each, including the last one.
❓ Predict Output
intermediateAccessing characters with at() method
What will be the output of this C++ code?
DSA C++
std::string s = "world"; for (size_t i = 0; i < s.length(); ++i) { std::cout << s.at(i); }
Attempts:
2 left
💡 Hint
The at() method returns the character at the given index without extra characters.
✗ Incorrect
The loop prints each character without spaces or separators, so the output is the string itself.
❓ Predict Output
advancedOutput of nested loops with string indexing
What is the output of this C++ code snippet?
DSA C++
std::string s = "abc"; for (int i = 0; i < s.size(); ++i) { for (int j = 0; j <= i; ++j) { std::cout << s[j]; } std::cout << " "; }
Attempts:
2 left
💡 Hint
The inner loop prints characters from start up to the current outer loop index.
✗ Incorrect
For i=0, prints 'a'; i=1 prints 'ab'; i=2 prints 'abc', each followed by a space.
❓ Predict Output
advancedResult of modifying characters via indexing
What is the output after running this C++ code?
DSA C++
std::string s = "test"; s[1] = 'a'; s[3] = 'p'; std::cout << s;
Attempts:
2 left
💡 Hint
Characters at index 1 and 3 are replaced.
✗ Incorrect
Original string is 'test'. s[1] = 'a' changes 'e' to 'a', s[3] = 'p' changes 't' to 'p'. Result is 'tasp'.
🧠 Conceptual
expertUnderstanding string traversal with iterators
Given the following C++ code, what is the output?
DSA C++
std::string s = "data"; for (auto it = s.begin(); it != s.end(); ++it) { if (*it == 'a') { std::cout << '*'; } else { std::cout << *it; } }
Attempts:
2 left
💡 Hint
The code replaces every 'a' character with '*'.
✗ Incorrect
The loop prints each character. When the character is 'a', it prints '*', else prints the character itself. So 'data' becomes 'd*t*'.
