C++ Program for the Range sum queries without updates?

We need to compute sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times.

Input:arr[] = {5, 6, 3, 4, 1 } i = 1, j =3
Output: 13

Explanation

6 + 3 + 4 = 13
sum[] = {5, 6+5, 3+6+5, 4+3+6+5, 1+4+3+6+5 }
sum[]={5,11,14,18,19}
sum[j]-sum[i-1]=sum[3]-sum[1-1]= sum[3]-sum[0]=18-5=13

The logic is very basic in this starting the loop form i index to till j index and sum up the elements between those indexes. But we can’t store them in extra variable so we will use another array where we add the array element with last array element and so on. And then from on j index we will subtract the i-1 index value;

Example

#include <iostream>
using namespace std;
int rangeSum(int i, int j, int sum[]) {
if (i == 0)
return sum[j];
return sum[j] - sum[i - 1];
}
int main() {
int arr[] = { 5, 6, 3, 4, 1 };
int n=5;
int sum[5];
sum[0] = arr[0];
for (int i = 1; i < n; i++) {
sum[i] = arr[i] + sum[i - 1];
}
cout << rangeSum(1, 3, sum) << endl;
return 0;
}

Output

13