7.9. Looping and counting¶
The active code below counts the number of times the letter
appears in a string
This program demonstrates a common idiom, called a counter. The
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. In the function, declare length, count, and index in that order.
Within the main function, declare city and letter in that order.
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.