Page 1 of 1

enthuware.ocajp.i.v7.2.1083

Posted: Thu Mar 15, 2018 7:49 am
by ashishrai.kv

Code: Select all

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?

Re: enthuware.ocajp.i.v7.2.1083

Posted: Thu Mar 15, 2018 12:23 pm
by admin
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.

Re: enthuware.ocajp.i.v7.2.1083

Posted: Thu Mar 15, 2018 3:55 pm
by ashishrai.kv
ok thanks.

Re: enthuware.ocajp.i.v7.2.1083

Posted: Wed Jul 18, 2018 1:30 am
by flex567
I think the point here is that after

Code: Select all

break middle;

the execution doesn't enter the second loop

Code: Select all

for (int j = 0; j < 3; j++)
but continuous with the first one ?

Code: Select all

for (int i = 0; i < 3; i++)

Re: enthuware.ocajp.i.v7.2.1083

Posted: Thu Dec 27, 2018 5:51 pm
by crazymind
My question is: why does ''counter++;" get execute after "break middle;" ? The code immediately goes to outer loop after ''break middle".

Re: enthuware.ocajp.i.v7.2.1083

Posted: Thu Dec 27, 2018 9:42 pm
by admin
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.

Re: enthuware.ocajp.i.v7.2.1083

Posted: Thu Dec 27, 2018 10:18 pm
by crazymind
Thanks. Do you mean that counter++ gets executed after break middle?
So counter++ will not get executed if I change it to break inner.

Re: enthuware.ocajp.i.v7.2.1083

Posted: Thu Dec 27, 2018 10:22 pm
by crazymind
sorry. I did not look this code carefully. I understand now.