For Loops with Arrays
Learn to use Java for loops by building a Weekly Step Tracker App that calculates the total and average steps over 7 days.
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 loop
with a counter (range-style): ...