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();
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With