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.

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.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

You have attempted 1 of 6 activities on this page