Skip to main content

Section 7.18 Looping and Counting

We will finish this chapter with a few more examples that show variations on the theme of iteration through the characters of a string. We will implement a few of the methods that we described earlier to show how they can be done.
The following program counts the number of times a particular letter, a_char, appears in a string. It is another example of the accumulator pattern that we have seen in previous chapters.
The function count takes a string and a character as its parameters. The for statement iterates through each character in the string and checks to see if the character is equal to the value of a_char. If so, the counting variable, letter_count, is incremented by one. When all characters have been processed, the letter_count is returned.