• Post Reply Bookmark Topic Watch Topic
  • New Topic

A question about review question in Chapter 2  RSS feed

 
Matthew Han
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,
I have a question about one of the review questions in Chapter 2
question 9: how many times will the following code print "Hello World"


the answer is this is a infinite loop, but I thought it was going to print out Hello World 10 times. I have a hard time to understand the answer explanation.

My idea is that i is 0 at the beginning, then turn to 1, print Hello World first time, go back to for(), check i still less than 10, then, i turns to 2, print Hello World again.

Thank you all,
 
Naziru Gelajo
Ranch Hand
Posts: 175
1
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Han wrote:Hi guys,
I have a question about one of the review questions in Chapter 2
question 9: how many times will the following code print "Hello World"


the answer is this is a infinite loop, but I thought it was going to print out Hello World 10 times. I have a hard time to understand the answer explanation.

My idea is that i is 0 at the beginning, then turn to 1, print Hello World first time, go back to for(), check i still less than 10, then, i turns to 2, print Hello World again.

Thank you all,


The reason it's an infinite loop is for a couple of reasons. Look at the for loop, typically speaking its structure is as follows: for (initiallization; conditional statement; incremental statement). The constructed loop that you linked has for i = 0 which is where i starts, i < 10 , however where is the incremental test. then on the next line of code, it says i = i++ so i = i but then increments by 1 when it is done executing the System.out.println() statement.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!