Skip to main content

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

Section 7.9 Looping and counting

Listing 7.9.1. This active code counts the number of times the letter 'a' appears in a string fruit .
This program demonstrates a common idiom, called a counter. The variable count is initialized to zero and then incremented each time we find an 'a'. (To increment is to increase by one; it is the opposite of decrement, and unrelated to excrement, which is a noun.) When we exit the loop, count contains the result: the total number of a’s.

Checkpoint 7.9.1.

What does the following code print?
int x = -5;
while (x < 0) {
  x = x + 1;
  cout << x << " ";
}
  • 5 4 3 2 1
  • Notice that x is negative.
  • -5 -4 -3 -2 -1
  • Notice that the value of x is incremented before it is printed.
  • -4 -3 -2 -1 0
  • The value of x is incremented before it is printed so the first value printed is -4.

Checkpoint 7.9.2.

As an exercise, encapsulate this code in a function named countLetters, and generalize it so that it accepts the string and the letter as arguments. In the function, declare length, count, and index in that order. Within the main function, declare city and letter in that order.

Checkpoint 7.9.3.

The following is the correct code for printing the even numbers from 0 to 10, but it also includes some extra code that you won’t need. Drag the needed blocks from the left and put them in the correct order on the right.

Checkpoint 7.9.4.

What is the value of counter right before main returns 0?
string word_1 = "understand";
string word_2 = "underwaa";

size_t end_1 = word_1.length();
size_t end_2 = word_2.length();

if ( end_2 < end_1 ) {
   end_1 = end_2;
}

size_t index = 0;
size_t counter = 0;

while ( index < end_1 ) {
  if ( word_1[index] == word_2[index] ) {
     counter = counter + 1;
  }
  else {
     counter = counter - 1;
  }
  index = index + 1;
}

return 0;
  • The code dosen’t reach return 0 because we index out of bounds in word_2.
  • We set end_1 to be the smaller of the two lengths so we don’t index out of bounds.
  • Not all the letters after index 4 differ in the two words.
  • We decrement the value of counter when we don’t have matching letters.
  • Correct! we have 6 matching letters and 2 differing letters upto the length of word_2.
You have attempted 1 of 5 activities on this page.