Can someone please help me do this java problem?

Write a method called int sumab that takes 2 integer parameters, a and b (b must be bigger) and returns the sum of all the integers from a to b. 

2 Answers

  • 8 months ago

    Learn C++ retard. Or any C language for that matter. 100x better than Java and JavaScript.

    • Commenter avatarLogin to reply the answers
  • 8 months ago

    There are two ways to get this done.  One is to loop to generate all int values from a to b:

    for (int value = a; value <= b; ++b) {

    .... [do something with value here]


    You can get the sum of all those value by declaring a variable outside the loop (initially zero) and adding each value into that variable.  The final value is your method result to return.

    The better way (I think) is to use the math you learned in Algebra 1 to sum an arithmetic sequence.  This sequence has (b - a) + 1 terms and the average value of an arithmetic sequence is always the average of the first and last terms (a + b)/2.

    Multiply the two numerators before dividing by 2 just in case (a+b) is odd: ( which case (b-a)+1 will be even.  The sum must by a whole number, right?)

        return (b - a + 1) * (b + a) / 2;

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.