Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will it "update" when it "break" from the inner "for" loop in java?

Tags:

java

The code shown below is designed to generate 30 different numbers in the range of 36 using nested for loop.

This example shows that when it break from the inner for loop, it would execute the "update" (in this example the "update" is ++i) in the outside "for" loop. But my teacher told me that it wouldn't.

But when I debug it, it did execute the "update". Am I correct?

public class array {

    public static void main(String[] args) {
        int a[] = new int[30];
        for( int i=0;i<a.length;++i)
        {
            a[i] = (int)( Math.random()*36 ) +1;
            for(int j=0;j<i;++j)
            {
                if(a[i]==a[j])
                {
                    --i;
                    break;
                }
            }
        }
        for( int num: a) System.out.print( num+" " ); 
        System.out.println();
    }
}
like image 911
syndory Avatar asked Dec 18 '22 19:12

syndory


1 Answers

That break breaks the inner loop. The outer loop continues with the update section of the for (++i). If your teacher told you it wouldn't do that ++i, he/she is mistaken. The inner update (++j) is not performed if that break is executed, but the outer one is.

Just to be clear we're talking about the same things:

int a[] = new int[30];
for (int i = 0; i < a.length; ++i) {
    // Outer update ----------^^^

    a[i] = (int) (Math.random() * 36) + 1;
    for (int j = 0; j < i; ++j) {
        // Inner update ---^^^

        if (a[i] == a[j]) {
            --i;
            break; // <==== This break
        }
    }
}

for (int num : a) {
    System.out.print(num + " ");
}
System.out.println();
like image 120
T.J. Crowder Avatar answered Mar 23 '23 11:03

T.J. Crowder