Respuesta :
Answer:
public static double sum(int a,int b){
int sum =0;
for(int i =a+1; i<b;i++){
sum = sum+i;
}
return sum;
}
Explanation:
A complete Java program that calls the method sum() is given below;
In creating the method sum; We used a for loop that starts at a+1 and ends at 1 less than b, this is because we want to grab the numbers between them and not including them.
In the body of the for loop, we add each element to the sum variable initially declared and initialized to zero.
public class TestClock {
public static void main(String[] args) {
int num1 = 5;
int num2 = 10;
System.out.println("The sum of numbers between "+num1+ " and "+num2+ " is "+sum(num1,num2));
}
public static double sum(int a,int b){
int sum =0;
for(int i =a+1; i<b;i++){
sum = sum+i;
}
return sum;
}
}
Answer:
//Method sum header declaration.
//The return type of the method be of type int,
//since the sum of integer numbers is an integer.
//It has the variables a and b as parameter
public static int sum(int a, int b){
//Since the method will sum numbers between a and b,
//it implies that a and b are not inclusive.
//Therefore, increment variable a by 1 before starting the loop
//and make sure the loop does not get to b
//by using the condition a < b rather than a <=b
a++;
//Declare and initialize to zero(0) a variable sum to hold the sum of the numbers
int sum = 0;
//Begin the while loop.
//At each cycle of the loop, add the value of variable a to sum
//and increment a by 1
while(a < b) {
sum = sum + a;
a++;
}
//at the end of the loop, return sum
return sum;
} // End of method sum
Explanation:
The above code has been written in Java. It also contains comments explaining every section of the code. Please go through the comments for better understanding.
The overall code without comments is given as follows;
public static int sum(int a, int b) {
a++;
int sum = 0;
while (a < b) {
sum = sum + a;
a++;
}
return sum;
}