224k views
2 votes
Write a function addOddMinusEven that takes two integers indicating the starting point and the end point. Then calculate the sum of all the odd integers minus the sum of all even integers between the two points. The calculation includes the starting point but excludes the end point. You can always assume the starting point is smaller than the end point.

1 Answer

1 vote

Answer:g

public static int addOddMinusEven(int start, int end){

int odd =0;

int even = 0;

for(int i =start; i<end; i++){

if(i%2==0){

even = even+i;

}

else{

odd = odd+i;

}

}

return odd-even;

}

}

Step-by-step explanation:

Using Java programming language:

  • The method addOddMinusEven() is created to accept two parameters of ints start and end
  • Using a for loop statement we iterate from start to end but not including end
  • Using a modulos operator we check for even and odds
  • The method then returns odd-even
  • See below a complete method with a call to the method addOddMinusEven()

public class num13 {

public static void main(String[] args) {

int start = 2;

int stop = 10;

System.out.println(addOddMinusEven(start,stop));

}

public static int addOddMinusEven(int start, int end){

int odd =0;

int even = 0;

for(int i =start; i<end; i++){

if(i%2==0){

even = even+i;

}

else{

odd = odd+i;

}

}

return odd-even;

}

}

User Cristian Curti
by
5.6k points