• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Break/Incrementation question

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I just have a question about this code:

public class Test{
public static void main(String[] args) {
int counter = 0;
outer: for(int i=0;i < 4; ++i)
middle: for(int j=0;j < 4; ++j)
inner: for(int k=0;k < 4; ++k) {
System.out.println("Hello - " + ++counter);
if((k % 4) ==0)
break outer;
}
}
}

The answer is meant to be Hello - 1 due to 0 mod 4 being 0 and thus the inner loop is only executed once but I would of thought since k is pre-incremented in the declaration of the for statement that k would never be 0 and be greater than 0 due to this pre-incrementation and thus wouldnt break to outer?

Does the incrementation happen only after one iteration of the for loop or something?

Any tips to help understand would be appreciated.

Dave
[ July 31, 2006: Message edited by: David Kennedy ]
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, the statements that are part of the for loop declaration



are only executed after the body of the loop.
 
David Kennedy
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cheers for the reply

That solves that for me.


Thanks
[ July 31, 2006: Message edited by: David Kennedy ]
reply
    Bookmark Topic Watch Topic
  • New Topic