<< Chapter < Page | Chapter >> Page > |
Some important things to notice about this algorithm:
minIdx
value if the array was indeed empty--it's an invalid value! It can't be set to a valid value because otherwise you can't tell the difference between a value that was never set and one that was.for
loop has two initialization statements separated by a comma.For convenience, Java 5.0 now offers a compact syntax used for traversing
all the elements of an array or of anything that subclasses type
Iterable
:
MyType[] myArray; // array is initialized with data somewherefor(MyType x: myArray){
// code involving x, i.e. each element in the array}
It is important to remember that this syntax is used when one wants to process every element in an array (or an
Iterable
object)
independent of order of processing because Java does not guarantee a traversal order.
Let's look at an algorithm where we might not want to process the entire array:
// Find the first index of a given value in an array
int idx = -1; // initialize the index to an invalid value.for(int j=0; j<myArray.length; j++) { //no initialization ; end index at length-1;
//increment index every time the loop is processed.if(desiredValue == myArray[j]) { // found match!idx = j; // save the index.
break; // break out of the loop.}
}
Notes:
idx
is -1 or not. Thus the value of
idx
must be checked before it is ever used.idx
variable cannot be used as the index inside the loop because one would not be able to tell if the desired value was found or not unless one also checked the length of the array. This is because if the desired value was never found,
idx
at the end of the loop would equal the length of the array, which is only an invalid value if you already know the length of the array.break
statement stops the loop right away and execution resumes at the point right after end of the loop.There is a counterpart to
break
called
continue
that causes the loop to immediately progress to the beginning of the next iteration. It is used much more rarely than
break
, usually in situations where there are convoluted and deeply nested
if
-
else
statements.
Can you see that the price of the compact syntax of for loops is a clear understandability of the process?
for
loops are actually a specialized version of
while
loops.
while
loops have no special provisions for initialization or loop incrementing, just the termination condition.
Notification Switch
Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?