What will the following program print?
class LoopTest{
public static void main(String args[]) {
int counter = 0;
outer:
for (int i = 0; i < 3; i++) {
middle:
for (int j = 0; j < 3; j++) {
inner:
for (int k = 0; k < 3; k++) {
if (k - j > 0) {
break middle;
}
counter++;
}
}
}
System.out.println(counter);
}
}
Is there any trick or way to go through the problems given above which have multiple loops running through, to check and get the answers?
Not really. You need write the values of the loop variables on a paper at each step. It sounds too much but usually the loops in the questions end rather quickly due to strategic placement of break/continue.
If you like our products and services, please help us by posting your review here.
No, break middle; will break the loop labelled "middle". The control will go to the next statement after middle loop, which means the next iteration of outer loop.
Also, break middle; is executed only if k - j > 0. You will need to write the values of the variables in each iteration to see why counter++ gets executed. Check the output shown in the explanation.
If you like our products and services, please help us by posting your review here.