ChunkierLizard ChunkierLizard - 2 months ago 15
Java Question

java loop sum integers

I'm have a question. So I need to write a program that asks the user to enter a nonzero integer value. I then need to use a loop to get the sum from 1 to the integer entered. Any help would be great.

Answer

This should work.

Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();

int sum = 0;
for (;val >= 1; val--) {
    sum += val;
}

System.out.println(sum);

It gets an integer from the console, then loops while decrementing the integer, adding up the total. In the for loop, the first statement (usually something like int i = 0 is omitted because we already have a variable, we just need to decrement it until we reach 1.