Summing+part+of+an+array

//by Richard Russell, October 2013 (original concept by Michael Hutton)//

The [|SUM] function returns the sum of all the elements of an array. It may occasionally be useful to discover the sum of only **part** of an array, but BBC BASIC doesn't have a built-in function to do that.

Of course it's straightforward to find the sum using a loop: code format="bb4w" total = 0 FOR index% = first% TO last% total += array(index%) NEXT code where **first%** and **last%** define the range of indices (inclusive) over which the sum should be calculated.

However this approach is relatively slow, especially if the number of elements being summed is large, and it would be desirable to have a faster method. Fortunately there is a way, although the code isn't very nice: code format="bb4w" DEF FN_SumPartialArray(d, first%, last%) LOCAL I%     I% = ^d(first%)-5 LOCAL ?I%, I%!1, a ?I% = 1 : I%!1 = last%-first%+1 !^a = I%     = SUM(a) code The array **a** must be the same type (i.e. have the same suffix character, if any) as the array being summed.

Note that during execution of the function the array contents are temporarily changed, so don't use this method if your program has a timer interrupt in which the array is accessed.

If errors are trapped (using ON ERROR) and you need your program to resume execution after an error (e.g. pressing the **Esc**ape key), add a statement to ensure the array contents are restored: code format="bb4w" DEF FN_SumPartialArray(d, first%, last%) LOCAL I%     I% = ^d(first%)-5 LOCAL ?I%, I%!1, a ON ERROR LOCAL RESTORE LOCAL : ERROR ERR, REPORT$ ?I% = 1 : I%!1 = last%-first%+1 !^a = I%     = SUM(a) code