Keeping a count of something and computing the sum of a range of values are two commonly occurring problems in programming. For example, you may want to write a program to find the number of students in your school who are 15 years old. Or you may want to write a program to find the sum of all even numbers between 1 to 100. Counters and Accumulators provide solutions to these commonly occurring problems, respectively.
Counters and Accumulators are not operators. They provide a general solution to the problems of counting and computing sum that can be used in many different situations.
Counters
Counters as the name suggests are variables which are used to keep a count. Let’s look at a BlueJ program to understand how to initialize and use counters.
This program finds the count of numbers between 1 to 100 that are divisible by 7
public class Counter
{
public void demoCounter() {
/*
* Declare and initialize
* counter with 0
*/
int count = 0;
for (int i = 1; i < 101; i++) {
if (i % 7 == 0) {
/*
* Increment the counter if
* number is divisible by 7
*/
count++;
}
}
System.out.println("Count of numbers divisible by 7 is " + count);
}
}
In this program, we are using the variable count as a counter. We first initialize it with 0. If the number is divisible by 7, we increment count’s value by 1. This way we use the variable count as a counter to find how many numbers between 1 to 100 are divisible by 7.
Let's execute the program and see its output:
Accumulators
Accumulators are variables which are used to calculate the sum of a set of values. Building on our previous example, let’s say this time we want to calculate the sum of all the numbers between 1 to 100 which are divisible by 7. Here is the BlueJ program for this problem:
public class Accumulator
{
public void demoAccumulator() {
/*
* Declare and initialize
* accumulator with 0
*/
int sum = 0;
for (int i = 1; i < 101; i++) {
if (i % 7 == 0) {
/*
* Add the number to the value
* of sum if divisible by 7
*/
sum += i;
}
}
System.out.println("Sum of numbers divisible by 7 is " + sum);
}
}
In this program, we use the variable sum as our accumulator. We first initialize it with 0. As we find more numbers divisible by 7, we keep on adding their value to sum. At the end of the for loop, variable sum contains the sum of all numbers between 1 to 100 which are divisible by 7.
Let's execute the program and see its output: