In-range Adder
In-range Adder in C++
#include <iostream>
int inRangeAdder(int start, int end) {
int sum = 0;
for (int i = start; i <= end; ++i) {
sum += i;
}
return sum;
}
int main() {
int start = 1;
int end = 5;
int result = inRangeAdder(start, end);
std::cout << "The sum of numbers from " << start << " to " << end << " is: " << result << std::endl;
return 0;
}
- Include the necessary header file for input/output stream.
- Define a function
inRangeAdder
that takes two integersstart
andend
as parameters and returns an integer. - Initialize a variable
sum
to store the sum of numbers. - Use a for loop to iterate from
start
toend
, adding each number to thesum
. - Return the final sum.
- In the
main
function, definestart
andend
variables. - Call the
inRangeAdder
function withstart
andend
as arguments and store the result in theresult
variable. - Output the result using the standard output stream.
I hope this helps!