Write a Java method named calculateSum
that takes two integer parameters, start
and end
, representing the starting and ending numbers of a range, inclusive. This method should calculate and return the sum of all the numbers within the range.
Use the following method signature:
public static int calculateSum(int start, int end)
For example, if start
is 1 and end
is 5, the method should calculate and return the sum of the numbers 1, 2, 3, 4, and 5, which is 15.
Write the calculateSum
method along with its appropriate method header and return statement in the code cell below.
Remember to include access modifiers, a valid method signature, and necessary declarations.
public class Main {
public static void main(String[] args) {
int start = 1;
int end = 5;
int sum = calculateSum(start, end);
System.out.println("The sum of numbers from " + start + " to " + end + " is: " + sum);
}
public static int calculateSum(int start, int end) {
int sum = 0;
for (int i = start; i <= end; i++) {
sum += i;
}
return sum;
}
}
The calculateSum
method takes two integer parameters, start
and end
, representing the starting and ending numbers of the range. It initializes the sum
variable to 0.
A for loop is used to iterate over each number from start
to end
, inclusive. The loop starts with i
initialized to start
, and the loop continues as long as i
is less than or equal to end
. After each iteration, i
is incremented by 1.
Inside the loop, the value of i
is added to the sum
variable. This accumulates the sum of all the numbers within the range.
After the loop ends, the sum
variable stores the final sum of all the numbers within the range. It is then returned by the method as the desired result.
In the given example, the main
method calls the calculateSum
method with start
value of 1 and end
value of 5. The calculated sum is stored in the sum
variable and printed to the console. The output will be:
The sum of numbers from 1 to 5 is: 15