int totalTemp = 0; int mondayHi = input.readInt("Monday's high temp?"); totalTemp = totalTemp + mondayHi; int tuesdayHi = input.readInt("Tuesday's high temp?"); totalTemp = totalTemp + tuesdayHi; int wednesdayHi = input.readInt("Wednesday's high temp?"); totalTemp = totalTemp + wednesdayHi; ... int averageHi = totalTemp / 7;This approach has some serious drawbacks. What are they? What we really want to say is something like:
For each day of the month (week or whatever period) get the high temperature and accumulate it. Afterwards, divide the total temperature by the number of days in the period.Java lets us express this algorithm almost verbatim:
int totalTemp = 0; int numDays = 30; for (int i=0; i < numDays; i=i+1) { int todaysHi = input.readInt("High temperature for day " + i); totalTemp = totalTemp + todaysHi; } int averageHi = totalTemp / numDays;The for-loop in Java has the following pattern:
for (<initializer-statement>; <condition-expression>; <update-statement>) { <body> }The semantics is as follows: First, the
initializer
statement
is executed. Then, while the condition-expression
is true, the body
statements, followed by the
update-statement
is executed.
Since so many for-loops contain statements like i=i+1 in their update step (indeed, incrementing by one is very common in other places too) you'll see the following shorthand used frequently:
i++; // means i=i+1
While there is rain on a given day, accumulate the total rainfall. Afterwards, calculate the average.This problem is not naturally counting loop -- it loops simply until some condition is true. Java supports this kind of loop too:
int todaysRainfall = input.readInt("Today's rainfall?"); int daysWithRain = 0; while (todaysRainfall > 0) { daysWithRain = daysWithRain + 1; totalRainfall = totalRainfall + todaysRainfall; todaysRainfall = input.readInt("Today's rainfall?"); } int averageRainfall = totalRainFall / daysWithRain;We can express this as a for loop, but it's not naturally a counting loop. It is worth convincing yourself, though, that every while loop can be expressed as a for loop, and vice-versa. For example, we could transform the above into a for loop:
int daysWithRain = 0; for (int todaysRainfall = input.readInt("Today's rainfall?"); todaysRainFall > 0; todaysRainfall = input.readInt("Today's rainfall?")) { daysWithRain = daysWithRain + 1; totalRainfall = totalRainfall + todaysRainfall; } int averageRainfall = totalRainFall / daysWithRain;In general, it's better style to use a for loop when the loop is naturally described as a counting loop -- a loop that iterates over a sequence or range of numeric values.