Understanding Accumulators in Programming
Accumulators are a fundamental concept in programming where a variable holds the total of several values by continuously updating its value through operations like addition or concatenation. This concept is often used in loops to keep track of cumulative results or occurrences, akin to using a calculator to sum up numbers. Additionally, counters are a specialized form of accumulators used to track the occurrence of specific events by incrementing a constant value.
Download Presentation
Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
E N D
Presentation Transcript
Accumulators in Programming Assumes you have knowledge of the assignment operator = and a loop
What is an accumulator? An accumulator is not new syntax, it is just a new way to using the assignment operator It is a logical concept that is used in most languages The general idea is that a variable is given the job of holding the total of several values. Total is in quotes because it is not always an arithmetic sum, it can be done using many different operations. An accumulator could hold the sum of 10 numbers, the concatenation ( sticking together ) of 5 strings, the product of 15 numbers, etc. An accumulator starts at a known value (like zero), and is changed by adding on a different value. The result is stored right back in the same variable.
Calculator Analogy Suppose you wanted to add up a bunch of numbers using a calculator You would first clear the display of the calculator so that it showed a zero. (You usually don t want previous results mixed in with your total.) You punch in a number and hit the + key The display shows the first number (since it s the sum of zero and the number) You punch in another number and hit + The display shows the sum of the two numbers entered. You repeat the process until you have entered as many numbers as you needed the sum of. The number in the display is your accumulator.
A Counter a special form of an accumulator Sometimes you need to know how many times something happens The number of aliens killed The number of numbers read in An accumulator is useful here too You can add a constant term to an accumulator variable If you do, that is called a counter A counter is a specialized form of an accumulator Just changes the accumulator by a constant value Num_count = Num_count + 1 DozenCount = DozenCount + 12