Reputation: 11
its about break with label, java programming. This program searches for the number 1 in an array.
public static void main(String[] args) {
int[][] arrayOfInts =
{{ 32, 87, 3, 589},
{ 12, 1076, 2000, 8},
{ 622, 127, 77, 955}};
int searchfor = 1;
int i = 0;
int j = 0;
boolean foundIt = false;
search:
for (; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++){
if (arrayOfInts [i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found "+ searchfor + " at " + i +", "+ j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
the part of code that i didnt understand is
search:
for (; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++){
if (arrayOfInts [i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
and why there is ";" in front of "i"??
Upvotes: 1
Views: 75
Reputation: 3340
This is the format of the for loop. The initialization
, termindation
, and increment
part can be blank.
for (initialization; termination; increment) {
statement(s)
}
In your code example, i
was initialized before the for loop.
It will be similar to this:
public static void main(String[] args) {
int[][] arrayOfInts = {{1,2}, {3, 4}};
int searchfor = 8;
boolean foundIt = false;
for (int i = 0; i < arrayOfInts.length; i++) {
for (int j = 0; j < arrayOfInts[i].length; j++){
if (arrayOfInts [i][j] == searchfor) {
foundIt = true;
break;
}
}
}
}
See: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Upvotes: 0
Reputation: 4045
For loop to (<intialize counter>;<check loop condition>;<modify counter>)
In you first for loop there is nothing to initialize hence ;
or (; i < arrayOfInts.length; i++) { // Selects i'th row of your array
for (j = 0; j < arrayOfInts[i].length; j++){ // Scans array by j'th column of the i'th row
if (arrayOfInts [i][j] == searchfor) { // matches the i'th row and j'th column value of the array
foundIt = true;
break search; // comes out of the column for loop
}
}
}
Upvotes: 2
Reputation: 5309
It's just an another way of writing for loop.
As i
is initialised outside before the for loop, there is no initialisation required in for loop.
Code 1:
for(int i=0;i<n;i++){}
Code 2:
int i=0;
for(;i<n;i++){}
The Code 1 and Code 2 mean the same thing.
Upvotes: 2