Java(BlueJ) Adding up all numbers between two integers

10,742

Solution 1

The easiest way to do this is to reuse what you already have. Let's rename your method first:

public void sumMonotonic(int a, int b)
{
    int result = 0;
    while (a <=b) {
       result+=a;
       a++; 
    }       
    System.out.println("The sum of all numbers is "+result); 
}

So sumMonotonic() only works if its first argument is no bigger than its second. But now we can define sum() like this:

public void sum(int a, int b)
{
    if (a<=b)
        sumMonotonic(a,b);
    else
        sumMonotonic(b,a);
}

This just invokes the other function with the arguments in the appropriate order.

Actually there's one other oddity that we might fix. It seems a little unidiomatic to have a sumMonotonic() method that does the printing. It would be better if it returned the sum, and if the sum() method did the printing. So we'd refactor it like this:

public int sumMonotonic(int a, int b)
{
    int result = 0;
    while (a <=b) {
       result+=a;
       a++; 
    }
    return result;
}

public void sum(int a, int b)
{
    int result;
    if (a<=b)
        result = sumMonotonic(a,b);
    else
        result = sumMonotonic(b,a);
    System.out.println("The sum of all numbers is "+result); 
}

Solution 2

public void Sum(int a,int b)
 {
       int result = 0;
       if(a>b) //swap them
       {
          result=a;
          a=b;
          b=result;
          result=0;
       }
        while (a <=b) {
        result+=a;
        a++; 
  }   

   System.out.println("The sum of all numbers is "+result); 
   }
Share:
10,742
james11
Author by

james11

Updated on June 29, 2022

Comments

  • james11
    james11 almost 2 years

    I'm creating a method to add up all numbers between two integers. I currently have:

    /**
     * Add up all numbers between two integers
     */
    public void Sum(int a,int b)
    {
       int result = 0;
        while (a <=b) 
        {
            result+=a;
            a++; 
        }   
    
        System.out.println("The sum of all numbers is "+result); 
    }
    

    This only works if a <= b. How do i also do it for if a > b ?

    I have to use a while loop

  • Tom
    Tom over 9 years
    I guess it would make more sense if the arguments are switched (Sum(a, b) and Sum(b, a)). The Sum method itself shouldn't care about that.
  • james11
    james11 over 9 years
    Exactly what i was looking for - Thanks!
  • Saif
    Saif over 9 years
    yah that efficient one i admit, if the calling context Sum(int a,int b) was visible in the question . @Tom