- Forward


Accumulator Arrays
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Recall:
    • We sometimes need to "keep track of" something across iterations using an accumulator
  • A Related Problem:
    • We need to "keep track of" multiple things across iterations
  • Solutions:
    • Sometimes it is best to use multiple different accumulators
    • Sometimes it is best to use an array of accumulators
An Example
Back SMYC Forward
  • The Setting:
    • A school that assign numeric grades on a scale of 0 to 100
  • The Need:
    • A summary report that shows the number of students that were in each centile (i.e., the 100s, the 90s, the 80s, etc...).
Review
Back SMYC Forward

Given what you know, you might proceed as follows:

javaexamples/programmingpatterns/accumulatorarrays/AccumulatorArraysAlternative.java (Fragment: declarations)
 
javaexamples/programmingpatterns/accumulatorarrays/AccumulatorArraysAlternative.java (Fragment: loop)
 
Shortcomings
Back SMYC Forward
  • All of the variables must be declared and initialized individually
  • The nested if statement that is used to update the appropriate accumulator is both awkward and error-prone
  • Since methods in Java can only return a single entity, you could not write a re-usable method to perform these calculations
Thinking About this Example
Back SMYC Forward
  • One Observation:
    • In situations like this (i.e., when you have multiple "related" values) it is better to use an array than to use individual variables
  • Another Observation:
    • Truncation can be used to determine the centiles (i.e., the indexes)
The Pattern
Back SMYC Forward
  1. Declare and initialize an array to hold the number of accumulators needed
  2. Create an algorithm for identifying the index of the particular accumulator that needs to be updated during a particular iteration
  3. Write a loop that calculates the index and updates the appropriate accumulator
Examples
Back SMYC Forward

The Grades Example

javaexamples/programmingpatterns/accumulatorarrays/AccumulatorArrays.java (Fragment: gradeHistogram)
 
Examples (cont.)
Back SMYC Forward

Counting Odds and Evens

javaexamples/programmingpatterns/accumulatorarrays/AccumulatorArrays.java (Fragment: oddsAndEvens)
 
Examples (cont.)
Back SMYC Forward

Counting Negatives, Zeros, and Positives

javaexamples/programmingpatterns/accumulatorarrays/AccumulatorArrays.java (Fragment: signs)
 
There's Always More to Learn
Back -