Each character in a string has a position called an index. Counting starts at 0. In "PARK", index 0 holds P, index 1 holds A, index 2 holds R, and index 3 holds K.
Square brackets select one character: word[0] reads the first character. The dot in word.size() requests an operation belonging to that string; the parentheses call it. size() reports how many characters this plain-ASCII string contains.
#include <iostream>
#include <string>
#include <cstddef>
int main() {
std::string word = "MAP";
for (std::size_t index = 0; index < word.size(); index = index + 1) {
std::cout << word[index] << '\n';
}
return 0;
}
std::size_t, provided by <cstddef>, is an unsigned integer type used for sizes and positions. It cannot represent negative positions. Using it for the loop index matches the kind of value returned by size().
The condition is strictly <, not <=: the last character's index is one less than the size. This loop also handles an empty string safely because its first check is false. Do not subtract 1 from an empty string's unsigned size or read a character without knowing that its position exists.
The supplied code is "BOOK", so reading its first character is safe. For the second task, write a loop in the space after the Walk: output statement. Print one character on each visit, without a newline inside the loop. The supplied newline after it finishes the whole line. The index should stop before code.size(), not visit that position.
first from index 0 of code. Expect First: B.std::size_t index loop from 0 while index < code.size() to print each character after the supplied Walk: label. Expect Walk: BOOK.Edit main.cpp, press Run to inspect the Console, then Submit to check your work.