User Tools

Site Tools


finding_20the_20partial_20sum_20of_20an_20array

Finding the partial sum of an array

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. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
finding_20the_20partial_20sum_20of_20an_20array.txt · Last modified: 2018/04/17 17:14 by tbest3112