Originally posted by Amit Basnak:
Hello All
I have two questions on Break and continue
1>how can you change the break statement shown below so that it breaks out of the inner ane middle loops and continues with the next iteration of the outer loop??
outer: for (intx=0;x<3;x++) {
middle: for (int y=0; y<3; y++){
if (y==1)
break;
}
}
}
Options
1> break inner;
2> break middle;
3> break outer;
4> continue
5> continue middle
The answer is break middle ; ***** BUT I dont understand why break middle *****
----------------------------------------------------------------------------
Question 2>
What is the o/p of the following program if you compile and run?
outer: for(int i=0;i< 2; i++)
{
for (int j=0;j<3;j++)
{
if(i==j)
{
continue outer;
}
System.out.println("The value of i is :" +i);
System.out.println("The value of i is :" +j);
}
}
the answer is
The value of i is :1
The value of j is :0
Can anyone explained me this logic
best regards
Amit
In your first question, you want to break from the inner loop but continue the outer loop, the break middle is correct.
think about it this way, if you enter an outer loop it iterates once encounters an inner loop this does all of its loops, then finishes the inner loop at this point the outer loop continues on its second loop, then inner loop starts all over again., hence you break out of inner to continue the outer.
your options were:
Options
1> break inner; //you don't have a lable of inner
2> break middle; //this breaks out of the middle loop but will continue with the outer loop
3> break outer; //this will break out of the outer and wont do another iteration of outer
4> continue //this will just continue with the current loop you are in
5> continue middle //this will continue with the next iteration of middle, which you want to leave
continue means to forget what lines are next just continue with teh next iteratin of the loop,
continue label, means forget everything else and go and do another iteration of the loop that is associated with that label.
break means break out of that immedialte loop immediately.
break label, means break out of the loop that is associated with that label.
in you second question when you come up to your if statement, you continue the outer loop, so the figures you get are 1 for i because it has done one loop, and 0 for j because you started the inner loop again.
eg.
Davy
[ March 26, 2004: Message edited by: Davy Kelly ]