# how do you find the sum of a sequence in Java

2020-03-26 java sequence

I really don't understand how to find the sum of a sequence in Java. For instance, the program will ask for the input of the first and last number of the sequence and add the sum of the sequence(3 + 4 + 5 = 12). My System.out.println() isn't working as well. Why is this?

``````import java.util.Scanner;

public class SumOfASequenceTheSequel {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("First number?");
int first = Integer.valueOf(scanner.nextLine());
System.out.println("Second number?");
int second = Integer.valueOf(scanner.nextLine());

int sum = 0;

int i = first;

while (i <= second) {
sum = sum + i;
i = i++;
}

System.out.println("The sum is " + sum);
}
}
``````

i++; is called Post Increment equal to `i = i + 1;` So you just need `i++;`, not `i = i++;`.

As others have pointed out, because you are doing post-increment and assignment in the same statement, (`i = i++;`), your program is running in an infinite loop.

You might want to change it to either a pre-increment assignment (`i = ++i;`) or even better a plain pre or post increment (`i++;`).

Look at this link to understand the difference between pre and post increment operators.

I will recommend a `for` loop instead of `while` loop for better readability. See the following snippet:

``````for(int i = first; i <= second; i++) {
sum = sum + i;
}
``````

If you like `Stream` API instead of traditional loops, you can also print the sum the following way:

`System.out.println("The sum is " + IntStream.rangeClosed(first, second).sum());`

On a side note, you might want to close the `Scanner` resource after you are done using it to avoid resource leak, like so: `scanner.close();`

`i = i++;` This statement is incorrect. Because you used post incremental. In this statement first assign i's value to i after increment value. but i's value not changes. Then this while loop become infinity loop. So you need remove assignment part and only need `i++;`. Also you can use pre incremental (`++i;`). If you use pre incremental, then `i = ++i;` statement fine. But value assignment is not need.

If you can replace while loop using for loop, then you don't meet this problem. For loop solution below. Below Code `sum += i;` equals to `sum = sum + i`

``````for (int i = first; i <= second; i++) {
sum += i;
}
``````

Related