Reputation: 7
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
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
Reputation: 21619
You have several issues.
val
instead of sum
. Since val
is scoped to the loop, this is a compile error.<=
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