• Post Reply Bookmark Topic Watch Topic
  • New Topic

Shouldn't I get 2 outputs instead of 3?  RSS feed

 
Nick Woods
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!