get sum of range
To get the sum of a range in C++, you can use a loop to iterate through the numbers within the range and add them up. Here's an example code with explanations for each step:
#include <iostream>
int main() {
int start = 1; // starting number of the range
int end = 10; // ending number of the range
int sum = 0; // variable to store the sum
for (int i = start; i <= end; i++) {
sum += i; // add the current number to the sum
}
std::cout << "The sum of the numbers from " << start << " to " << end << " is: " << sum << std::endl;
return 0;
}
Explanation:
We include the
<iostream>
library to be able to use thestd::cout
andstd::endl
functions for output.We declare and initialize three variables:
start
,end
, andsum
.start
represents the starting number of the range,end
represents the ending number of the range, andsum
will store the sum of the numbers.We use a
for
loop to iterate through the numbers within the range. The loop variablei
is initialized with the value ofstart
, and it will continue as long asi
is less than or equal toend
. After each iteration,i
is incremented by 1.Inside the loop, we add the current value of
i
to thesum
using the+=
operator. This accumulates the sum of all the numbers within the range.After the loop, we use
std::cout
to display the result. We output a message that includes the starting and ending numbers of the range, along with the calculated sum.Finally, we return 0 to indicate successful execution of the program.
By running this code, you will get the sum of the numbers from the specified range.