3️⃣

9.3 Iterating through Arrays

Chapter Table of Contents

#️⃣
Ch. 9 Arrays

Section Table of Contents

It’s easy enough when you have an array of size 3 to manually assign elements. But in the real world, you usually deal with huge sets of data that might require an array with thousands of elements. How do we iterate through an array of that length? Enter the for loop and for each loop.

For Loop

// initialize array int[] numbers = {12, 34, 56, 78, 90); // for loop for (int index = 0; index < numbers.length; index++) { System.out.println(numbers[index]); }
As you can see from the code above, we are using a for loop to iterate through each index in the array, from 0 (the first index) up to numbers.length - 1 (the last index). This allows us to do things to each element, such as printing it (which is what happens above) or assigning elements.

For Each Loop

// for each loop for (int n: numbers) { System.out.println(n); }
You will often find yourself iterating through an array from start to finish. Because of this, Java has a convenient type of for loop called a for each loop, which allows you to do this with less typing. It’s also a lot more readable. (Note that you can only use for each loops on something that is iterable, such as an array.)
The highlighted portion of the code is read: “for each int n in numbers.” If I wanted to describe what was happening in the entire loop, I would say, “for each int n in numbers, print n.” Don’t get scared of the variable n — it’s simply a placeholder, a way to refer to the current element that you’re dealing with. (Note that I can name it whatever I want, as long as it follows Java variable naming rules.)
This is the generalized format of a for each loop:
for (elementType elementName: iterableObject) { // do stuff }
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.