Enhanced for Loop for Arrays
Explore the enhanced for loop in Java to efficiently traverse arrays without using index variables. Understand how this loop iterates by copying elements, affecting how changes to the loop variable do not alter the original array. This lesson helps you write cleaner array traversal code for AP Computer Science.
We'll cover the following...
Java provides a special kind of for loop that can be used with arrays. This loop is much easier to write because it doesn’t involve an index variable or the use of []. Let’s get started.
The for each loop
Introduction
To set up a for each loop, look at the snippet below:
for (datatype variable: arrayname)
The datatype specifies the type of values in the array called arrayname. The variable refers to the enhanced for loop variable. It reads: for each variable value in arrayname.
Example
Let’s look at an example.
Initially, we create an int type array. Look at line 7. We add the header for the for each loop (enhanced for loop), which reads: for each n in num. This means that the ...