This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

can't figure out simple while loop  RSS feed

 
Aditya Gohil
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the below program:

public class Loopy {

public static void main (String []args) {


int x = 1;

System.out.println ("This is before the Loop");

System.out.println ("The value of x is " +x);

while (x < 5) {
System.out.println ("This is during the loop");

x = x+1;


System.out.println ("The value of x is " + x);

}
System.out.println ("This is after the Loop");
}

} // end of the program

The output shows value of x till 5 even though the 'while' condition clearly states that x is less than 5 (x<5)

In the same program if I interchange the position of lines in bold (as shown below) the Program runs just fine and shows the value of x only till 4

public class Loopy {

public static void main (String []args) {


int x = 1;

System.out.println ("This is before the Loop");

System.out.println ("The value of x is " +x);

while (x < 5) {
System.out.println ("This is during the loop");

System.out.println ("The value of x is " + x);

x = x+1;


}
System.out.println ("This is after the Loop");
} // end of the program


Can someone please explain the reason behind this?

Thanks a lot in advance.
 
Junilu Lacar
Sheriff
Posts: 11138
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's because statements are executed in the order that they appear in the source code.

If x is currently 4, then you add 1 to it thus making x equal to 5, then displaying the value of x will show 5, of course.

If, however, you display the value x before you add 1 to it, then the program will show 4.
 
Junilu Lacar
Sheriff
Posts: 11138
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW, Welcome to the Ranch!

In the future, please UseCodeTags (←click on that link to see how) when posting code.
 
Aditya Gohil
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:It's because statements are executed in the order that they appear in the source code.

If x is currently 4, then you add 1 to it thus making x equal to 5, then displaying the value of x will show 5, of course.

If, however, you display the value x before you add 1 to it, then the program will show 4.


Hey, thanks a for the reply. Will take care about the code tags in the future..
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!