| Author |
simple code
|
sony kolla
Greenhorn
Joined: Sep 25, 2008
Posts: 14
|
|
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
Joined: Oct 07, 2008
Posts: 5
|
|
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
Joined: Apr 28, 2008
Posts: 71
|
|
If you indent your loops it becomes easier to follow the program execution..
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
|
|
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.
|
 |
 |
|
|
subject: simple code
|
|
|