- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program for Range sum queries without updates?
Here we will see how to get the sum of elements from index i to index j in an array. This is basically the range query. The task is easy by just running one loop from index i to j, and calculate the sum. But we have to care about that this kind of range query will be executed multiple times. So if we use the mentioned method, it will take much time. To solve this problem using more efficient way we can get the cumulative sum at first, then the range sum can be found in constant time. Let us see the algorithm to get the idea.
Algorithm
rangeSum(arr, i, j)
begin c_arr := cumulative sum of arr if i = 0, then return c_arr[j]; return c_arr[j] – c_arr[i-1] end
Example
#include<iostream> using namespace std; void cumulativeSum(int c_arr[], int arr[], int n){ c_arr[0] = arr[0]; for(int i = 1; i<n; i++){ c_arr[i] = arr[i] + c_arr[i-1]; } } int rangeSum(int c_arr[], int i, int j){ if( i == 0){ return c_arr[j]; } return c_arr[j] - c_arr[i-1]; } main() { int data[] = {5, 4, 32, 8, 74, 14, 23, 65}; int n = sizeof(data)/sizeof(data[0]); int c_arr[n]; cumulativeSum(c_arr, data, n); //get cumulative sum cout << "Range sum from index (2 to 5): " << rangeSum(c_arr, 2, 5) << endl; cout << "Range sum from index (0 to 3): " << rangeSum(c_arr, 0, 3) << endl; cout << "Range sum from index (4 to 7): " << rangeSum(c_arr, 4, 7) << endl; }
Output
Range sum from index (2 to 5): 128 Range sum from index (0 to 3): 49 Range sum from index (4 to 7): 176
- Related Articles
- C++ Program for the Range sum queries without updates?
- Range Sum Queries Without Updates using C++
- Queries to find maximum product pair in range with updates in C++
- C++ Range Sum Queries and Update with Square Root
- Array range queries for elements with frequency same as value in C Program?
- Find the Initial Array from given array after range sum queries in C++
- Program to find kpr sum for all queries for a given list of numbers in Python
- Binary Indexed Tree: Range Update and Range Queries in C++
- Queries for counts of array elements with values in given range in C++
- Gadget Updates For The Month
- Google Updates for the Month
- Gadget Updates for the Week
- Min-Max Range Queries in Array in C++
- Queries to update a given index and find gcd in range in C++ Program
- Queries for number of array elements in a range with Kth Bit Set using C++

Advertisements