Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Iterating Through 1D Array
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Now that we know what an array is and what it contains, let's see how we can apply loops to help us accomplish tasks with arrays. For example, you want to know the sum of all the elements in an array. Instead of summing each element together in your head, you can write a for loop to do the work for you. Check out the code below for an example.
Iteration1DExample.java
package exlcode;
public class Iteration1DExample {
public static int[] exampleVariableOne = {0, 1, 2, 3, 4, 5, 6, 7, 8};
public static int sum = 0;
public static void main(String[] args) {
// for loops are the most common method when
// iterating through an 1D array
for (int count = 0; count < exampleVariableOne.length; count++) {
// add each element to sum
sum += exampleVariableOne[count];
}
// print the total sum of all the elements in the array
System.out.println(sum);
}
}
The for statement has the condition count<exampleVariableOne.length, which makes sure that every element in the array is added to sum before the for loop is terminated. Why do we use '<'? Because the last index of the array is always array.length-1, so count cannot be equal to or greater than exampleVariableOne.length. If we do not specify this, a runtime error may occur.
The for loop above is a prime example of the loops used when dealing with one-dimensional arrays. As you master using a for loop and accessing the elements in an array, you will start writing more complicated programs that deal with large amounts of data. Being able to iterate through arrays using loops is important because arrays cannot be directly printed to the console. System.out.println(arrayname) won't work.