7.9. Looping and counting¶
The active code below counts the number of times the letter 'a'
appears in a string fruit.
1#include <cstddef>
2#include <iostream>
3#include <string>
4
5using std::size_t;
6
7int main() {
8 std::string fruit = "banana";
9 std::size_t count = 0;
10
11 std::size_t index = 0;
12 while (index < fruit.size()) {
13 if (fruit[index] == 'a') {
14 count = count + 1;
15 }
16 index = index + 1;
17 }
18 std::cout << count;
19}
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.
Q1
What does the following code print?
1int x = -5;
2while (x < 0) {
3 x = x + 1;
4 cout << x << ' ';
5}
Q2
As an exercise, encapsulate this code in a function named
count_letter, and generalize it so that it accepts the string and
the letter as arguments. In the function, declare count and index in that order.
Within the main function, declare city and letter in that order.
-
cout << count_letter(city, letter); } -
return count; } -
count = count + 1; } -
index = index + 1; } -
char letter = 'e'; -
if (s[index] == letter) { -
int main() { -
std::size_t count = 0; -
std::size_t count_letter(string s, char letter) { -
std::size_t index = 0; -
string city = "New Baltimore"; -
while (index < s.size()) {
Q3
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.
-
x = x + 2; } -
cout << x << '\n'; -
while (x < 10) { #distractor -
while (x <= 10) { -
x = 0; -
x = x + 1; #distractor
Q4
What is the value of counter right before main returns 0?
1string word_1 = "understand";
2string word_2 = "underwaa";
3
4size_t end_1 = word_1.length();
5size_t end_2 = word_2.length();
6
7if ( end_2 < end_1 ){
8 end_1 = end_2;
9}
10
11size_t index = 0;
12size_t counter = 0;
13
14while ( index < end_1 ) {
15 if ( word_1[index] == word_2[index] ){
16 counter = counter + 1;
17 }
18 else {
19 counter = counter - 1;
20 }
21 index = index + 1;
22}
23
24return 0;