- Forward


Accumulators
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • A Question and Likely Response:
    • Ask someone how to add a column of numbers by hand
    • They will probably say something like "just add them up"
  • An Easy Challenge:
    • They'll probably be able to succeed with a column of fifty single-digit numbers
  • Making it Harder:
    • Talk to them while their adding the numbers
  • A Suggestion:
    • Tell them to write things down as they go
Review
Back SMYC Forward
  • Sometimes:
    • Each iteration of a loop is independent of other iterations
  • Frequently:
    • This isn't the case and we need to "keep track of" something across iterations
  • An Example:
    • Calculating the sum of the elements of a double[]
Review (cont.)
Back SMYC Forward

Getting Started

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: loop)
 

What "needs to be done" at each iteration?

Thinking About the Problem
Back SMYC Forward
  • Finding the Sum of a Long List of Numbers:
    • People commonly keep a running total (e.g., 7 plus 3 is 10, plus 2 is 12, ...)
  • Programming this Algorithm:
    • You need a variable for the running total
The Pattern
Back SMYC Forward
  • Getting Started:
    • Decide the type of the running value (i.e., the accumulator)
  • Initialization:
    • Declare and initialize the accumulator outside of the loop
  • Iteration:
    • Update the accumulator in the body of the loop (if necessary)
Types of Accumulators
Back SMYC Forward
  • Numeric (e.g., int, double):
    • Sums/Totals
    • Counts/Tallies (e.g., of positive numbers, even numbers)
    • Minima
    • Maxima
  • String:
    • Concatenation of words/lines
  • boolean:
    • Containment/existence checks
    • Identical elements check
A Numeric Example
Back SMYC Forward

Finding the Maximum

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: max)
 
A Boolean Example
Back SMYC Forward

Containment

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: contains)
 
Examples with Multiple Accumulators
Back SMYC Forward

The Mean After Dropping the Lowest Value

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: droplowest)
 
An Example with a Common "Twist"
Back SMYC Forward

The Index of the Largest Element

javaexamples/programmingpatterns/accumulators/Accumulators.java (Fragment: argmax)
 
There's Always More to Learn
Back -