Repeat work with loops and arrays
Visit each array item and accumulate a result with a loop.
- Create an array and process its values with a for loop.
An array stores a fixed-size sequence of values of one type. Its indexes start at zero. A for loop can visit each valid index or use an enhanced for loop to visit each value. Loops let a program process many items without repeating the same statement by hand.
1int[] scores = {80, 90, 100};
2int total = 0;
3for (int score : scores) {
4 total += score;
5}
6System.out.println(total);270
Use array.length to get the number of items. A classic loop often uses i < array.length; using <= can access an index past the last item. An enhanced for loop is simpler when you need values but do not need their indexes.
Key takeaways
Create an array and process its values with a for loop.
Java checks types as it compiles your source.
Use compiler messages as clues about what needs fixing.
Lesson quiz
4 questions · pass with 3 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Java
Write Java in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.
Sum a row of numbers
Read an integer count followed by that many integers. Print their sum. Use an array and a loop.
- Three values
- One negative value
Java is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…