Flash cards
Review the key moves
What is the main idea behind Java Arrays Loop?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___[] cars = {"Volvo", "BMW", "Ford", "Mazda"};Put the learning moves in the order that makes the concept easiest to apply.
Loop Through an Array
You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
This example creates an array of strings and then uses a for loop to print each element, one by one:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}Here is a similar example with numbers. We create an array of integers and use a for loop to print each value:
Example
int[] numbers = {10, 20, 30, 40};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}Calculate the Sum of Elements
Now that you know how to work with arrays and loops, let's use them together to calculate the sum of all elements in an array:
Example
int[] numbers = {1, 5, 10, 25};
int sum = 0;
// Loop through the array and add each element to sum
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println("The sum is: " + sum);Loop Through an Array with For-Each
There is also a " for-each " loop, which is used exclusively to loop through elements in an array (or other data structures ):
Syntax
for ( type
variable
: arrayname ) {
// code block to be executed
}The colon ( : ) is read as "in". So you can read the loop as: "for each variable in array" .
The following example uses a for-each loop to print all elements in the cars array:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String car : cars) {
System.out.println(car);
}This means: for each String in the cars array (here called car ), print its value.
Compared to a regular for loop, the for-each loop is easier to write and read because it does not need a counter (like i < cars.length ). However, it only gives you the values, not their positions (indexes) in the array.
So, if you need both the position (index) of each element and its value, a regular for loop is the right choice. For example, when printing seat numbers in a theater row, you need to show both the seat number (the index) and who is sitting there (the value):
Example
String[] seats = {"Jenny", "Liam", "Angie", "Bo"};
for (int i = 0; i < seats.length; i++) {
System.out.println("Seat number " + i + " is taken by " + seats[i]);
}Note
The for-each loop is great when you only need to read elements. If you want to change the elements later, or keep track of their index, use a regular for loop instead.