Using an Accumulator

From Progzoo
Revision as of 00:12, 8 December 2007 by Andr3w (Talk | contribs) (Using an accumulator to count.)

Jump to: navigation, search

When using an accumulating variable there are three stages:

Initialise
We declare our accumulator and set it to an initial values.
Update
Inside the loop we update the accumulator - we take into account the current data item.
Output/use
After the loop our accumulator contains the required value. We use it or output it.

Using an accumulator to add.

Print the total of all of the numbers

  • We initialise to 0.
  • We add to the accumulator.
  • The value printed is the sum 0+2+7+1+1.


[Font] [Default] [Show] [Resize] [History] [Profile]

Using an accumulator to count.

Line: 123 DOMDocument::loadXML(): AttValue: " or ' expected in Entity, line: 3
Line: 123 DOMDocument::loadXML(): attributes construct error in Entity, line: 3
Line: 123 DOMDocument::loadXML(): Couldn't find end of Start Tag p line 3 in Entity, line: 3
Line: 123 DOMDocument::loadXML(): Opening and ending tag mismatch: question line 1 and p in Entity, line: 3
Line: 123 DOMDocument::loadXML(): Extra content at the end of the document in Entity, line: 4

Using an accumulator to count on a condition.

Count the number of 1s in the list

  • We initialise to 0.
  • We increment the accumulator only if the current value equals 1.


[Font] [Default] [Show] [Resize] [History] [Profile]

Using an accumulator to multiply.


  • We initialise to 1.
  • We multiply the accumulator.
  • The value printed is the product: 1*2*7*1*1


[Font] [Default] [Show] [Resize] [History] [Profile]

Using an accumulator to find the maximum.


  • We initialise to 0.
  • We take the max.
  • The value printed is the largest:
    max(max(max(max(0,2),7),1),1)


[Font] [Default] [Show] [Resize] [History] [Profile]

Using an accumulator to concatenate.


  • We initialise to "".
  • We concatenate the next value.
  • Each time i gets converted to a string and is put at the end.
  • The answer is ""+2+7+1+1


[Font] [Default] [Show] [Resize] [History] [Profile]

Using two accumulators to find the mean.


  • We initialise both to 0.
  • We add to the sum and increment the count.
  • We divide the sum by the count to get the average.


[Font] [Default] [Show] [Resize] [History] [Profile]

Using an accumulator to calculate.


  • We initialise to 0.
  • We multiply by the radix and add the next digit.
  • By the end the number 2 has been multiplied by 10 three times, the number has been multiplied by 10 twice...
  • 10*(10*(10*2+7)+1)+1


[Font] [Default] [Show] [Resize] [History] [Profile]