For Loops
Introduction.
We have presented decision structures where program flow branches based on
some conditions. Now we need to present material about
looping in order to repeat code
segments based on some criteria.
The looping can be based purely on some sort of counting, or it can be based on more abstract criteria. This page focuses on looping based on changes in a counter. The counter can increase in increments of one or more, or it can decrease in decrements of one or more. Usually it just increases by one for each repetition of the loop. The counter can start at any value, though it usually starts at zero or one. The standard syntax for a for loop conforms to the following for (start value; upper limit; increment) structure.
Though the criteria within the parentheses can be quite different. The upperLimit needs to be obtained from somewhere else in the program or from the user. The syntax can be adjusted so that counter <= upperLimit. The syntax can also be adjusted to start at a different value. Finally, the increment can be a decrement and either can be different than one. If there is only a single code statement after the for (counter = 0, counter < upperLimit; counter++ ) there doesn't need to be any braces.
Some Verbal Examples. Assume you have just bought a car on a five year plan with monthly payments. You might get the following oversimplified code segment.
Well, this can go on and on. Obviously, some of these depend on having other sources for inputs. A Simple Code Example. At some point in time you may have tried to find the sum of consecutive positive integers 1 + 2 + 3 + ... + N. While there is a closed form solution to this, we will write computer code to solve this problem based on the user's inputs for N. You should call the application SumOfN.java. |
import javax.swing.JOptionPane; public class SumOfN {
} // end SumOfN |
We do our typical imports, declarations and
initializations so I won't discuss these any more. We do our typical
error trapping on the inputs and for the parsing. Of greater
interest is the for loop.
There isn't much else to say. |