Reputation: 197
I don't understand this code. One of my friend thought me to use the boolean to make it work. I don't really understand when he explains it. Why is the found
in the for
loop?
int id = input.nextInt();
boolean found = false;
for (int i = 0; i < z && !found; i++){
if (arr[i].getId() == id){
found = true;
index = i;
}
}
Upvotes: 2
Views: 27523
Reputation: 2031
The conditional statement inside the for loop reads
i < z && !found
When 'found' is true, the for loop will stop looping. You can read more about for loops here
For loop syntax looks like this:
for (initialize ; condition ; increment) {}
It's also possible to replace your for loop with a while loop.
int i = 0;
int found = false;
while(i < z && !found) {
if(arr[i].getId()==id){
found = true;
index = i;
}
}
In both cases, you can simplify your conditional using the "break" keyword. The break keyword causes a loop to exit immediately. This may or may not be the appropriate solution here, but it does show another way to handle these kinds of loops.
for(int i=0; i<z; i++){
if(arr[i].getId()==id){
index = i;
break;
}
}
Upvotes: 1
Reputation: 393781
The i<z && !found
part of the for loop is the condition, which must be true in order for the loop to continue. Adding the !found
part means that the loop would terminate when either found
is true or i>=z
, whichever happens first. Without that condition, the loop would always run z
times, even if a match (i.e. arr[i].getId()==id
) is found on the first iteration. Therefore, this condition is an optimization that reduces the running time of the loop.
An alternative to the !found
condition is using the break
keyword to terminate the loop :
for(int i=0; i<z; i++){
if(arr[i].getId()==id){
found = true;
index = i;
break;
}
}
Upvotes: 0
Reputation: 11
Here "Boolean" is using to terminate the loop as soon as the inputted "id" found in your array. The good thing is the compiler don't have to search until last index wheres "id" already found.
Upvotes: 1