Sparse data often stores only nonzero entries and summarizes those compact values.

Program

Play the program to include a different number of stored nonzero values.

nonzero_sum.f90
program nonzero_sum_demo
    implicit none
    integer :: indices(4)
    integer :: values(4)
    integer :: active_count
    integer :: i
    integer :: total

    indices = [2, 5, 9, 12]
    values = [4, 7, 3, 6]
    active_count = 
    total = 0
    do i = 1, active_count
        total = total + values(i)
    end do
    print '(I0, 1X, I0)', active_count, total
end program nonzero_sum_demo
program nonzero_sum_demo
    implicit none
    integer :: indices(4)
    integer :: values(4)
    integer :: active_count
    integer :: i
    integer :: total

    indices = [2, 5, 9, 12]
    values = [4, 7, 3, 6]
    active_count = 
    total = 0
    do i = 1, active_count
        total = total + values(i)
    end do
    print '(I0, 1X, I0)', active_count, total
end program nonzero_sum_demo
program nonzero_sum_demo
    implicit none
    integer :: indices(4)
    integer :: values(4)
    integer :: active_count
    integer :: i
    integer :: total

    indices = [2, 5, 9, 12]
    values = [4, 7, 3, 6]
    active_count = 
    total = 0
    do i = 1, active_count
        total = total + values(i)
    end do
    print '(I0, 1X, I0)', active_count, total
end program nonzero_sum_demo
sparse storage `indices` records where the stored values belong in the full shape.
active entries `active_count` chooses how many compact entries are present.
compact sum The summary loops over stored values, not over every possible position.