• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt on continue loop

 
R .sourav nayak
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

could someone explain me how will be the out put 3 4 5 from the following code


1. int i, j;
2. lab: for( i = 0; i < 6; i++ ){
3. for( j = 5; j > 2; j-- ){
4. if( i == j ) {
5. System.out.print(" " + j ) ;
6. continue lab ;
7. }
8. }
9. }

i think, the statement at line 5 never reached.so there is no output.

thanks in advance,
reena
 
Tim LeMaster
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just step through it

1st through outer loop i=0
inner loop tests i == j for j = 5 4 3

2nd through outer loop i=1
inner loop tests i == j for j = 5 4 3

...

All the continue does is once a match is found jumps to the next interation of the outer loop. The label is needed to keep continue from just acting upon the inner loop.

Bonus point - whats the output if the continue is removed?
[ September 19, 2006: Message edited by: Tim LeMaster ]
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

it will reach only when i = 3, 4, 5. Add one println statement and you will find out why.
 
R .sourav nayak
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much Tim and wise for the immediate replay
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic