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.
- 5 4 3 2 1
- Notice that x is negative.
- -5 -4 -3 -2 -1
- Notice that the value of x is incremented before it is printed.
- -4 -3 -2 -1 0
- The value of x is incremented before it is printed so the first value printed is -4.
Q-2: What does the following code print?
1int x = -5;
2while (x < 0) {
3 x = x + 1;
4 cout << x << " ";
5}
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.
- The code dosen't reach
return 0
because we index out of bounds inword_2
. - We set
end_1
to be the smaller of the two lengths so we don't index out of bounds. - 2
- Not all the letters after index 4 differ in the two words.
- 3
- We decrement the value of counter when we don't have matching letters.
- 4
- Correct! we have 6 matching letters and 2 differing letters upto the length of
word_2
.
Q-5: What is the value of counter
right before main returns 0?
1string word_1 = "understand";
2string word_2 = "underwaa";
3
4int end_1 = word_1.length();
5int end_2 = word_2.length();
6
7if ( end_2 < end_1 ){
8 end_1 = end_2;
9}
10
11int index = 0;
12int counter = 0;
13
14while ( index < end_1 ) {
15 if ( word_1[index] == word_2[index] ){
16 counter = counter + 1;
17 }
18
19 else {
20 counter = counter - 1;
21 }
22 index = index + 1;
23}
24
25return 0;