• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

simple code

 
sony kolla
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Exercise1b {

public static void main(String[] args) {

int x = 5;
while(x > 1)
{
x = x - 1;
if(x < 3)
{
System.out.println("small x");
}

}
}

}

Output

small x
small x

my doubt is here x = 5 then why this condition

if(x < 3)
{
System.out.println("small x");
}

working and it is giving small x as output. i know this is a silly and simple doubt please dont mind please anyone answer me thank you.
 
Jason Kirk
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sony,

In this case, when you first enter the while loop, x = 4 since you have x = x - 1 in the beginning. When x becomes 2 in the loop, then the program hits the "if" statement which prints "small x". The program goes to the beginning of the while loop again, sees that x = 2 (so it passes), then it decrements x by 1 so now x = 1. The program would hit the "if" statement since x = 1 is less than 3 so it would print "small x" again. Since x = 1 now, the program would exit out of the while loop.

Hope that probably over-complicated explanation helps.

- Jason
 
Jules Bach
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you indent your loops it becomes easier to follow the program execution..

 
Campbell Ritchie
Sheriff
Pie
Posts: 50173
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jules Bach is quite right; we have code tags which preserve the indentation and ought to be used whenever you post code.

And that is not a silly question at all; lots of people get confused about that sort of loop.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic