get range sum
To get the range sum in C++, you can use a loop to iterate through the range and accumulate the sum of the elements. Here's an example of how you can do this:
#include <iostream>
#include <vector>
int getRangeSum(const std::vector<int>& nums, int start, int end) {
int sum = 0;
for (int i = start; i <= end; i++) {
sum += nums[i];
}
return sum;
}
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int start = 2;
int end = 6;
int rangeSum = getRangeSum(nums, start, end);
std::cout << "The sum of the range from " << start << " to " << end << " is: " << rangeSum << std::endl;
return 0;
}
Let's break down the steps involved:
First, we include the necessary headers,
iostream
for input/output operations andvector
for using a dynamic array-like structure.We define a function called
getRangeSum
that takes a vector of integers (nums
) and two integer parameters (start
andend
) representing the range.Inside the
getRangeSum
function, we initialize a variablesum
to 0. This variable will accumulate the sum of the elements in the range.We use a
for
loop to iterate through the range fromstart
toend
. The loop variablei
is initialized withstart
and the loop continues as long asi
is less than or equal toend
. In each iteration, we add the value at indexi
ofnums
to thesum
variable.After the loop, we return the calculated
sum
.In the
main
function, we define a vectornums
containing some sample numbers.We also define the
start
andend
variables to specify the range for which we want to calculate the sum.We call the
getRangeSum
function with thenums
,start
, andend
variables as arguments, and store the result in therangeSum
variable.Finally, we print the result using
cout
and the<<
operator.
This code will output the sum of the range from 2 to 6, which in this case is 20.