
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- C++ Program for 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
- Gadget Updates For The Month
- Google Updates for the Month
- Gadget Updates for the Week
- Binary Indexed Tree: Range Update and Range Queries in C++
- Queries for counts of array elements with values in given range in C++
- Queries for bitwise AND in the index range [L, R] of the given Array using C++
- Queries for Bitwise OR in the Index Range [L, R] of the Given Array using C++
- Min-Max Range Queries in Array in C++

Advertisements