7.9. Looping and counting

The active code below 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.

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.

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

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.

You have attempted 1 of 6 activities on this page