The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Strings and things Looping and Counting | ||
Looping and Counting
int length = fruit.length(); int count = 0; int index = 0; while (index < length) { if (fruit[index] == 'a') { count = count + 1; } index = index + 1; } cout << count << endl; 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. 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. As a second exercise, rewrite this function so that instead of traversing the string, it uses the version of find we wrote in the previous section.
|
||
Home Strings and things Looping and Counting |