Hello all, great forum that have been a great source of information for me over the past many weeks. So now I decided to join up.

I am currently trying to write a partial sum function as part of a much larger program I once wrote in Fortran. I am trying to figure out how to take the sum of a select amount of entries in an array. In general I want to be able to do other operations then sum but for now it is the most simple.

Example: In an array of size N I want to be able to only know the sum of the elements from n to k.

In Fortran this is simple since it is part of the syntax.

sum(DataArray(n : N - k))

Where N and k are integers. It takes the sum of all elements in DataArray from 1 til element N - k.

My current attempt in C++ is by using a while loop so I only get the values from 0 up to a certain point, and then take it from there.

for (int i = 0; i < N ; i++)
                while(i < N - k) PartSum +=DataArray[i];

However it just keeps adding up numbers and never breaks off again.
Any help would be much appreciated.

>while(i < N - k) PartSum +=DataArray; i is never updated in this loop.

Okay so I have tried to change into an if loop instead since as you said i is never updated, so far it produces finite results, just hope it is the right ones.
Thanks for your help Narue

for (int i = 0; i < N ; i++)
                if( i  < N - k ) PartSum += DataArray[i];
                else break;

No need for two loops here:
Given an array (arr), the starint index (j), the ending index (k) and the number of elements in the array (n):

int sum =0;
for( int i=j; i<k; i++ )
    sum += arr[i];

You will need to ensure that i >= 0 and k <= n


I noticed that you use the terminating condition i < n-k. Just substitute this into the termination criteria (middle statement) in the for loop

Of course! Thanks a lot.