Java Reference
In-Depth Information
4.2 Cumulative Algorithms
The more you program, the more you will find that certain patterns emerge. Many
common algorithms involve accumulating an answer step by step. In this section, we
will explore some of the most common cumulative algorithms .
Cumulative Algorithm
An operation in which an overall value is computed incrementally, often
using a loop.
For example, you might use a cumulative algorithm over a set of numbers to com-
pute the average value or to find the largest number.
Cumulative Sum
You'll often want to find the sum of a series of numbers. One way to do this is to
declare a different variable for each value you want to include, but that would not be
a practical solution: If you have to add a hundred numbers together, you won't want
to declare a hundred different variables. Fortunately, there is a simpler way.
The trick is to keep a running tally of the result and process one number at a time. For
example, to add to a variable called sum , you would write the following line of code:
sum = sum + next;
Alternatively, you could use the shorthand assignment operator:
sum += next;
The preceding statement takes the existing value of sum , adds the value of a vari-
able called next , and stores the result as the new value of sum . This operation is per-
formed for each number to be summed. Notice that when you execute this statement
for the first time sum does not have a value. To get around this, you initialize sum to a
value that will not affect the answer: 0 .
Here is a pseudocode description of the cumulative sum algorithm:
sum = 0.
for (all numbers to sum) {
obtain "next".
sum += next.
}
To implement this algorithm, you must decide how many times to go through the
loop and how to obtain a next value. Here is an interactive program that prompts the
user for the number of numbers to add together and for the numbers themselves:
 
Search WWH ::




Custom Search