Search⌘ K
AI Features

For Loops with Arrays

Explore how to implement for loops with arrays in Java by building a Weekly Step Tracker application that stores seven days of step data, sums the steps, and computes the average daily steps. This lesson helps you understand iterating over collections using standard and enhanced for loops, enabling efficient data processing for real-world projects.

The project

You’ve already created a Step Tracker that records daily steps. At the moment, though, it only works when you enter the numbers manually. Printing a single line, such as “Steps today: 3,000,” can be useful, but it doesn’t show your progress over an entire week. What you need instead is a system that stores seven days of step counts in a list, and then loops through them to calculate both the total and the average.

Your project: Build a Weekly Step Tracker that keeps seven days’ worth of steps in a list, uses a loop to add them up, and calculates the average steps per day.

The programming concept

A while loop repeats while a condition is true. However, sometimes you already know exactly how many times you want something to be repeated. For example: “Say hello 5 times.” Do you think a for loop or a while loop is more natural for that?

The for loop in Java can work in two ways.

  1. For loop with a counter (range-style): ...