Page 2 of 3
There are a number of patterns that keep occurring when we use iteration.
Pattern 1: Summation and Averaging
There are three steps to this pattern:
- Prepare an accumulator (i.e. a memory slot where things get added up).
- Iterate over a number of items (e.g. the contents of an array) and add them all to the accumulator.
- Finish, and either announce the sum or divide by the number of items and announce the average.
The following program fragment calculates the average of the sum of the first imax integers:
int sum = 0.0;
for(int i = 1;i<=imax;i++)
{
sum = sum + i;
}
float average = sum/float(imax);
It is much more likely that we will want to calculate the average of the values stored in some array (and this time it will be an array of floating point values):
float sum = 0.0;
for(int i = 1;i<imax;i++) // This time imax is the number of elements in the array
{ // Remember that the address of the last element is [imax-1].
sum = sum + array[i];
}
float average = sum/float(imax);