• Post Reply Bookmark Topic Watch Topic
  • New Topic

Infinite while loop  RSS feed

 
Zack Mathew
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I came across this code while reading a book. The author here says, the program will run in an infinite while loop. Why is that?
According to me, since x=1, the compiler enters the while loop. Since 1 is not greater than 3, it never enters the if loop, and just comes out without printing anything. The author's modified code is --



Can someone please explain? I am sorry if its a silly question, but to be honest I have no idea. I am willing to learn from all the experts out here
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sjsu student,

Welcome to CodeRanch!

Please UseRealName.

It is good that you have used code tags in your first post itself.

Now, coming to your question:

Code snippet 1:
sjsu student wrote:Since 1 is not greater than 3, it never enters the if loop, and just comes out without printing anything

You are right about this. But it will come 'out' of if condition. It will still go and check condition of while loop (x<10). That condition would always be true and it will be infinite loop.

Code snippet 2:
I'm not sure what is your 'exact' doubt about this one, but all I can say is - the code is increasing value of x inside the while loop. So, at some point of time, it will be 10 and the while loop will be broken. Also, due to if condition, it will print values from 4 to 10.

I hope this helps.
 
Zack Mathew
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I got it now. Always makes difficult things simple when somebody else explains it to you
Thank you for such a quick response.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note: An if-statement is not a loop.
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Zack Mathew wrote:Okay, I got it now. Always makes difficult things simple when somebody else explains it to you
Thank you for such a quick response.

You are welcome.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!