Using an accumulator
A common pattern in a loop is to initialize a variable outside the loop, and update it during each iteration (or some of the iterations). Here is an example you may have seen before, a static method that counts the number of times the character 'p' occurs in a string:
public static int countPs(String s)
{
int total = 0;
for (int i = 0; i < s.length(); i += 1)
{
// if the character is a 'p', add 1 to the total
char c = s.charAt(i);
if (c == 'p')
{
total += 1;
}
}
return total;
}
Here is a less obvious example. How would you create the reverse of a string? The idea is to build the result string one character at a time, in a loop. In pseudocode we want something like:
start with an empty result string
for each character c in the string, starting from the end
append c to the end of the result string
public static String reverse(String s)
{
String result = ""; // start with empty string
for (int i = s.length() - 1; i >= 0; i = i - 1)
{
result += s.charAt(i); // add on characters one at a time
}
return result;
}
Note that this is another example of the accumulator pattern, where the "accumulator" variable is a string and the operation is concatenation.