Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

2.5 Iteration — counting while traversing

Lesson

Accumulating over a traversal

Combine the two patterns you know: traverse a string, and keep a running count. Look at each character with charAt, test it, and update a counter when it matches. Characters are compared with == and a single-quote literal like 'a'.


Worked example — count the letter a

String s = "banana";
int count = 0;
for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == 'a') {
        count++;
    }
}
System.out.println(count);   // 3

▶ Try it: run this (there are 3 a's in banana). Change the word or the target letter 'a' and re-run.



What does the count loop above print for "banana"?


Type what this prints:

String s = "apple";
int count = 0;
for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == 'p') {
        count++;
    }
}
System.out.println(count);

True or false?


Order the lines to count how many times 'a' appears in s.