Hi guys,

I want to find the sum of numbers(inclusive) between TWO integers inputted by user.

Example: if user enters 1 and 4, then it outputs: Sum = 10

I just started my code:

public static void main(String[] args) {
        int number1 = 0,number2 = 0,Sum = 0;
        Scanner input = new Scanner(System.in);
        System.out.print("first integer:");
        number1 = input.nextInt();
        System.out.print("second integer:");
        number2 = input.nextInt();

    }

How can I do it? Do I have to use loops?

Dani AI

Generated

Short answer: you don't have to use a loop. There are two common approaches — iterate and accumulate (easy to reason about) or compute the total in constant time (no loop). 's quick one-line add is incorrect for a range; correctly flagged the closed‑form approach. Important gotchas to watch: make the endpoints inclusive, handle the case where the first input is larger than the second, and avoid intermediate overflow when using int.

A compact, safe Java helper that handles swapped endpoints and uses 64-bit arithmetic:

static long sumRange(int a, int b) {
    long start = Math.min(a, b);
    long end   = Math.max(a, b);
    long count = end - start + 1L;
    return (start + end) * count / 2L;
}

This returns 10 for sumRange(1, 4). The method casts to long early so the multiplication won't overflow for any two int inputs. If you expect values beyond the int range, use BigInteger:

static java.math.BigInteger sumRangeBig(java.math.BigInteger a, java.math.BigInteger b) {
    java.math.BigInteger start = a.min(b);
    java.math.BigInteger end   = a.max(b);
    java.math.BigInteger count = end.subtract(start).add(java.math.BigInteger.ONE);
    return start.add(end).multiply(count).divide(java.math.BigInteger.valueOf(2));
}

If simplicity matters and the range is small, a loop with a long accumulator is fine — just remember to include both endpoints and to swap if needed. Common bugs to avoid: off‑by‑one (exclusive vs inclusive), assuming inputs are ordered, and doing arithmetic in int where intermediate results exceed 32 bits.

Recommended Answers

All 2 Replies

You don't need to use loops.
You can

System.out.println(number1+number1+number2+number2);

unless you need to create a function.

private static int sumInclusive(int number1, int number2)
{
   return number1+number1+number2+number2;
}

well known method:

(( 1stNumber + 2ndNumber ) * numberOfNumbers) / 2

eg. 1st Number = 4 2nd = number 8

( ( 4 + 8 ) * ( 8 - 4 + 1 ) ) / 2
( 12 * 5 ) / 2
= 30

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.