Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 7.5 Traversal

A common thing to do with a string is start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. A natural way to encode a traversal is with a while statement.

Note 7.5.1.

On some machines, comparing an int to the output from length will generate a type error. This is because the length function returns an unsigned integer type. To keep the variable type consistent, you should use size_t rather than int for the type of the counter you use to keep track of the current index in the string.
Listing 7.5.1. This active code outputs each letter of string fruit using a while loop.
This loop traverses the string and outputs each letter on a line by itself. Notice that the condition is index < lengthfruit, which means that when index is equal to the length of the string, the condition is false and the body of the loop is not executed. The last character we access is the one with the index fruit.length()-1.
The name of the loop variable is index. An index is a variable or value used to specify one member of an ordered set, in this case the set of characters in the string. The index indicates (hence the name) which one you want. The set has to be ordered so that each letter has an index and each index refers to a single character.
As an exercise, write a function that takes an string as an argument and that outputs the letters backwards, all on one line.

Checkpoint 7.5.1.

Try writing the reverseWord function in the commented section of this active code. If done correctly, the program should output “hello” backwards. If you get stuck, you can reveal the hint below for help.
Hint.

Activity 7.5.1.

Let’s write the code for the reverseWord function. reverseWord should take a string as a parameter and output the letters backwards.

Checkpoint 7.5.2.

How many times is the letter o printed by the following statements?
string s = "coding rocks";
size_t i = 1;
while (i < s.length()) {
  cout << s[i] << endl;
  i = i + 2;
}
  • i goes through the odd numbers starting at 1.
  • Yes, i goes through the odd numbers starting at 1. o is at position 1 and 8.
  • There are 2 o characters but idx does not take on the correct index values for both.

Checkpoint 7.5.3.

What is printed when the code is run?
string truth = "engr101";
size_t index = 0;
int counter = 0;
while (index < truth.length()) {
  cout << truth[index] << " ";
  index = index + counter;
  counter = counter + 1;
}
  • e e n r 1
  • Correct! the values of index are 0 0 1 3 6. After this while loop ends.
  • e e e e e
  • We are updating the value of of index. Not doing so would make it an infinte loop!
  • e e n r
  • Recalculate the values of index at each stage and consider which ones are &lt 7.
You have attempted 1 of 5 activities on this page.