Lesson 6: Counters and Accumulators

Counters and accumulators are vital factors in repetition. Many programmers find it difficult to differentiate between the two. A counter indicates the amount of times a loop body has been executed, without being a counted loop. Counters are composed of two main elements: initial value and the incrementing value. The initial value is similar to a declaration section, because it gives the counter a value, somewhat like a constant. Once given the initial value, the counter is then incremented by the value specified by the programmer. The counter is different than a counted loop due to the fact that a counter does not exit the loop statement.

var counter: int
counter := 0
loop 
	counter:= counter +1 
	put counter, " ".. 
	exit when counter = 10 
end loop 
			

An example of a counter is above. What this loop statement does is that it exits when the loop body has been executed 10 times, perfectly displaying the purpose of a counter.

Accumulators

Accumulators are basically the same thing as counters. They require an initial value as well as an incrementing value. The only difference between the two is that an accumulator uses a variable to increment by. Here is an example:

loop
	put “mark:” ..
	get mark
	sum := sum + mark
	put sum
end loop

The “sum” in that loop statement is an accumulator because it is incremented by whatever the user inputs, in this case, the mark.
			

Valid XHTML 1.0 Strict Valid CSS! Valid CSS!