For Loops with Arrays
Explore how to use for loops with arrays to efficiently process data in Java. Learn to build a Weekly Step Tracker that sums and averages daily step counts stored in an array. Understand both counter-based and enhanced for loops, and apply these concepts to create practical projects like a Weekly Sleep Tracker. This lesson helps you automate repetition and gain confidence in working with arrays and loops.
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.
For loopwith a counter (range-style): ...