programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Shouldn't I get 2 outputs instead of 3?

Nick Woods
Greenhorn
Posts: 3
Here's my program:
public class JavaProgram {
public static void main (String[] args) {
int x = 8;
while (x > 5) {
System.out.println("Carrots and potatoes");
x = x-1;
}
System.out.println("Bananas);
}
}

The output i get is:
Carrots and potatoes
Carrots and potatoes
Carrots and potatoes
Bananas

Shouldn't i have Carrots and potatoes only twice since first time (x = 8-1 so first "x" is 7 and then x = 7-1 so next "x" is 6. So why do i get 3 outputs since the 3rd x would be equal and would not satisfy the (bigger than) condition?

Paweł Baczyński
Bartender
Posts: 2083
44
• 1
The condition is checked before the body of the loop is executed.
So, first x is 8, then 7, then 6, then 5.
When x is 5 the loop condition is false and the loop completes.

fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
• 1
You set x to 8.
You check to see if x is greater than 5. it is.
You print "Carrots and potatoes".
You reduce the value of x by 1, so x is 7.
You go back to the top of the loop.

You check to see if x is greater than 5. it is.
You print "Carrots and potatoes".
You reduce the value of x by 1, so x is 6.
You go back to the top of the loop.

You check to see if x is greater than 5. it is.
You print "Carrots and potatoes".
You reduce the value of x by 1, so x is 5.
You go back to the top of the loop.

You check to see if x is greater than 5. it is not.
You skip the loop body
You print Bananas.

Fix World
Greenhorn
Posts: 2
Nick Woods wrote:Here's my program:
public class JavaProgram {
public static void main (String[] args) {
int x = 8;
while (x > 5) {
System.out.println("Carrots and potatoes");
x = x-1;
}
System.out.println("Bananas);
}
}

The output i get is:
Carrots and potatoes
Carrots and potatoes
Carrots and potatoes
Bananas

Shouldn't i have Carrots and potatoes only twice since first time (x = 8-1 so first "x" is 7 and then x = 7-1 so next "x" is 6. So why do i get 3 outputs since the 3rd x would be equal and would not satisfy the (bigger than) condition?

I modified your program to print values of x at every step, hope the output makes the result clear.

And the output is

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.