8.4 Counter and Accumulator Variables


8.4 Counter and Accumulator Variables

Counters and accumulators are variables in an algorithm (and in the corresponding program), each serving a specific purpose. These variables should be well documented.

8.4.1 Counters

A counter variable has the purpose of storing the number of times that some condition occurs in the algorithm.

Note

A counter variable is of type integer and is incremented every time some specific condition occurs. The variable must be initialized to a given value, which is usually zero.

Suppose that in the salary problem, there is a need to count the number of employees with salary greater than $45,000. The name of the variable is num_high_sal and its initial value is zero. The variable declaration is:

       integer num_high_sal = 0 

Within the while loop, if the salary of the employee is greater than $45,000.00, the counter variable is incremented. The pseudo-code statement is:

       increment num_high_sal 

This counter variable is included in the implementation for class Salarym, as described previously. After the while loop, the following KJP statement prints the value of the counter variable num_sal:

       display "Employees with salary > 45000: ", num_sal 

8.4.2 Accumulators

An accumulator variable stores partial results of repeated additions to it. The value added is normally that of another variable. The type of an accumulator variable depends of the type of the variable being added. The initial value of an accumulator variable is normally set to zero.

For example, assume the salary problem requires the total salary increase for all employees. A new variable of type real is declared, the name of this variable is total_increase. The data declaration for this variable is:

       real total_increase = 0.0    // accumulator 

The algorithm calculates the summation of salary increases for every employee. The following statement is included in the while loop to accumulate the salary increase in variable total_increase:

       add increase to total_increase 

After the endwhile statement, the value of the accumulator variable total_increase is printed. The pseudo-code statement to print the string "Total amount of salary increase" and the value of total_increase is:

       display "Total salary increase: ", total_increase 

The KJP implementation for class Salarym for the salary problem includes the calculation of the total amount of salary increase.




Object-Oriented Programming(c) From Problem Solving to Java
Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)
ISBN: 1584502878
EAN: 2147483647
Year: 2005
Pages: 184

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net