finding_20the_20partial_20sum_20of_20an_20array

*by Richard Russell, July 2015*

The **SUM()** function returns the sum of all the elements in a numeric array, and it is much faster than summing the elements yourself in a loop. However you have no control over how many elements are summed: it is always the entire array. To find the sum of the first **n** elements of an array you can use a user-defined function as follows:

DIM array(999) array() = 1 PRINT FNsum(array(), 500)

This program prints the value 500, being the sum of the first 500 elements of the array (0 to 499 inclusive). Here is the **FNsum()** function itself:

DEF FNsum(a(), N%) IF DIM(a())<>1 ERROR 0, "Array must be one-dimensional" LOCAL !(!^a()+1) !(!^a()+1) = N% = SUM(a())

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information

finding_20the_20partial_20sum_20of_20an_20array.txt · Last modified: 2018/04/17 16:14 by tbest3112

Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International