plants tho plants tho - 9 days ago 4
Java Question

How do I use a while-statement properly?

My code below prints my desired ouput:

The sum is 45
.

int sum = 0, i = 1;
while (i < 10) {
sum = sum + i;
i++;
} System.out.println("The sum is " + sum);


Why doesn't my program work if I write this code below instead?

int sum = 0;
while (sum < 10) {
sum = sum + 1;
} System.out.println("The sum is " + sum);


The output becomes
The sum is 10
instead of
The sum is 45
.

Answer

As stated by others in the comments you need to replace while(sum<10) by while(sum<45). And to understand it you could print out the value of sum in the loop (actually debugging your code might be better but maybe that's a step too far right now).

    int sum = 0;
    while (sum<45){ // <-- this is where you went wrong
        System.out.println("sum: " + sum);
        sum = sum + 1;

    }
    System.out.println("Finished! The final sum is "+ sum);
Comments