Kate
Kate

Reputation: 7

Sum of numbers between int low and int high; Java

I am trying to create a code in Java and I know this is wrong but I need a little help:

Given two integers low and high representing a range, return the sum of the integers in that range. For example, if low is 12 and high is 18, the returned values should be the sum of 12, 13, 14, 15, 16, 17, and 18, which is 105. If low is greater than high, return 0.

The solution I have is (I know it's not right, don't murder me pls):

public int sumRange(int low, int high)
{
    int sum = 0;
    for (int val = int low; val < int high; val++)
        sum += val;
    return val;
}

Upvotes: 0

Views: 4607

Answers (2)

RaffleBuffle
RaffleBuffle

Reputation: 5455

Or you could use math, although you have to be careful of overflow if high is very large:

public static int sumRange(int low, int high)
{
  return high >= low ? (high*(high+1) - low*(low-1))/2 : 0;
}

Upvotes: 3

Paul Rooney
Paul Rooney

Reputation: 21619

You have several issues.

  1. Incorrect loop syntax. You don't need to redeclare the type of existing variables.
  2. You return val instead of sum. Since val is scoped to the loop, this is a compile error.
  3. Your loop ends one too early. It doesn't include the largest value. To include it use <= rather than <.

Fixed code

public class RangeTest1 {

    public static void main(String[] args){

        System.out.println(sumRange(12, 18)); // prints 105
        System.out.println(sumRange(18, 12)); // prints 0
        System.out.println(sumRange(18, 18)); // prints 18
    }

    public static int sumRange(int low, int high)
    {
        int sum = 0;

        for (int val = low; val <= high; val++){
            sum += val;
        }

        return sum;
    }
}

You get the 0 if low is greater than high for free, as the loop never runs any iterations if this is the case. The initial value of 0 remains and is returned.

Upvotes: 3

Related Questions