Reputation: 11
I have to write a program that adds all the odd numbers between two bounds. I got it to add the odd numbers, however I can't get it to work if one of the bounds is a negative. This is the code I have already.
import java.util.Scanner;
/**
Computes a sum of odd integers between two bounds.
Input: a, the lower bound (may be odd or even).
Input: b, the upper bound (may be odd or even).
Output: sum of odd integers between a and b (inclusive).
*/
public class OddSum
{
public static void main(String[] args)
{
// Read values for a and b
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int sum = 0;
int swap;
if(a > b) {
swap = a;
a = b;
b = swap;
}
for (int i = a; i <=b; i++){
if (i % 2 ==1)
sum +=i;
}
System.out.println(sum);
}
}
Upvotes: 1
Views: 702
Reputation: 1126
You need to use i % 2 != 0
as your condition to check whether a number is odd or not because the condition you're currently using unfortunately won't work for negative numbers.
After you've sorted out whether a or b should be first, you could get the sum in one line using IntStream
:
int sum = IntStream.rangeClosed(a, b).filter(i -> i % 2 != 0).sum();
This will take the sum of all odd numbers. Don't forget to import
import java.util.stream.IntStream;
Cheers!
Upvotes: 2
Reputation: 201447
Rather then testing i
for oddness every loop iteration, I would suggest you start with the first odd number following your lowest value in range and then increment by 2 in the loop. Something like,
int a = in.nextInt();
int b = in.nextInt();
int lo = Math.min(a, b);
int hi = Math.max(a, b);
if (lo % 2 == 0) { // <-- ensure that lo is odd.
lo++;
}
int sum = 0;
for (int i = lo; i <= hi; i += 2) {
sum += i;
}
System.out.println(sum);
Upvotes: 3
Reputation: 37645
Annoyingly, the condition for an odd number is
n % 2 != 0
n % 2 == 1
does not work for negative odd numbers because n % 2
gives -1
.
Upvotes: 3