Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Loop..continue...break

 
vinita Kh
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
y answer is break middle, i think it should be break outer, nebody plz explain.
How can you change the break statement below so that it breaks out of the inner and middle loops and continues with the next iteration of the outer loop?
outer: for ( int x =0; x < 3; x++ ) {
middle: for ( int y=0; y < 3; y++ ) {
if ( y == 1) {
break;
}
}
}
A) continue middle
B) break middle:
C) break outer:
D) continue
 
Chintan Rajyaguru
Ranch Hand
Posts: 341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you put a break statement, execution jumps out of the loop and executes the line next to the ending curly brace of the loop.
Now pay attention to this part of the question, "continues with the next iteration of the outer loop"
When does the next iteration of outer loop start? Exactly where middle loop ends and hence you have to break middle loop to start the next iteration of outer loop.
By the way I don;t see any inner loop in the question
 
vinita Kh
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks chintan!
May be he's talking about if condition as the inner loop.
 
luco zhao
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vinita Kh:
y answer is break middle, i think it should be break outer, nebody plz explain.
How can you change the break statement below so that it breaks out of the inner and middle loops and continues with the next iteration of the outer loop?
outer: for ( int x =0; x < 3; x++ ) {
middle: for ( int y=0; y < 3; y++ ) {
if ( y == 1) {
break;
}
}
}
A) continue middle
B) break middle:
C) break outer:
D) continue


I was wondering whether "break middle" has the same effect as "continue outer"? 3x.
 
Eduard Manas
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by luco zhao:

I was wondering whether "break middle" has the same effect as "continue outer"? 3x.


Luco,
In this case both "break middle" and "continue outer" have exactly the same effect. However, there is a slight difference between the one and the other:
* "continue outer" will start the next iteration of the outer loop, ignoring any code after middle loop in outer loop.
* "break middle" will execute the code after middle loop before starting the next iteration of outer loop.
As in this case we don't have any code after middle loop in outer loop, this difference is not relevant.
Hope it helps
Eduard
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic