• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is a for-loop broken out of as soon as the condition is not met?  RSS feed

 
R Pats
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For example, I am testing something w/ the following code:



And it is only printing out:

Number: 8

I don't exactly understand why it is not starting the for loop again how that I have updated b & e?
 
Claude Moore
Ranch Hand
Posts: 892
8
IBM DB2 Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simply because initialization expression in a for loop is executed exactly once, not at every iteration.
 
Liutauras Vilda
Marshal
Posts: 4657
320
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
R Pats, welcome to the Ranch.

Claude basically answered right to the point. In order to achieve desired behaviour, you can try to use while loop, that should work.
 
Junilu Lacar
Sheriff
Posts: 11165
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe I'm missing something but what exactly is the desired behavior? What was the desired output of this program?
 
Claude Moore
Ranch Hand
Posts: 892
8
IBM DB2 Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:What was the desired output of this program?

This makes me guess you didn't write that piece of code...
Where did you take it from ? Looks like it is an example from a tutorial or handbook aimed to make the reader understand how iteration in java (for, while and do .. while) works
 
Liutauras Vilda
Marshal
Posts: 4657
320
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:Maybe I'm missing something but what exactly is the desired behavior?
Based on the users question below, I assumed user expected loop control to be reset to 0 when i hits 8 (in fact during the first iteration). By changing assignment on line 5 to i = 0 program would satisfy quote below. Is it what OP expects? I'm not that sure.

R Pats wrote:I don't exactly understand why it is not starting the for loop again how that I have updated b & e?
By the way, my advice earlier to use while loop wasn't accurate. As wrote above, you can achieve that by amending assignment at line 5. But, as Junilu rightly said, you should define the expected output after program gets executed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!