| Author |
Infinite while loop
|
Zack Mathew
Greenhorn
Joined: Apr 03, 2012
Posts: 2
|
|
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
Joined: Dec 08, 2010
Posts: 1295
|
|
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.
|
Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD)
|
 |
Zack Mathew
Greenhorn
Joined: Apr 03, 2012
Posts: 2
|
|
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
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
|
Note: An if-statement is not a loop.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Anayonkar Shivalkar
Bartender
Joined: Dec 08, 2010
Posts: 1295
|
|
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.
|
 |
 |
|
|
subject: Infinite while loop
|
|
|