Skip to content
Related Articles

Related Articles

Improve Article
C++ Program for Range sum queries without updates
  • Last Updated : 06 Dec, 2018

Given an array arr of integers of size n. 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.

Examples:

Input : arr[] = {1, 2, 3, 4, 5}
        i = 1, j = 3
        i = 2, j = 4
Output :  9
         12         

Input : arr[] = {1, 2, 3, 4, 5}
        i = 0, j = 4 
        i = 1, j = 2 
Output : 15
          5




// CPP program to find sum between two indexes
// when there is no update.
#include <bits/stdc++.h>
using namespace std;
  
void preCompute(int arr[], int n, int pre[])
{
    pre[0] = arr[0];
    for (int i = 1; i < n; i++)
        pre[i] = arr[i] + pre[i - 1];
}
  
// Returns sum of elements in arr[i..j]
// It is assumed that i <= j
int rangeSum(int i, int j, int pre[])
{
    if (i == 0)
        return pre[j];
  
    return pre[j] - pre[i - 1];
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    int pre[n];
    preCompute(arr, n, pre);
    cout << rangeSum(1, 3, pre) << endl;
    cout << rangeSum(2, 4, pre) << endl;
  
    return 0;
}
Output:
9
12

Please refer complete article on Range sum queries without updates for more details!

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :