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.

for (counter = 0; counter < upperLimit; counter++ )

{

program statements
that are executed
while looping occurs;

}

 

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.

for (counter = 0, counter < upperLimit; counter++ )

single program statement executes at each iteration;

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.

for (paymentNumber = 1; paymentNumber <= 60; paymentNumber++)
{

make a car payment

}
 

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
{

public static void main( String args[] )
{

int upperLimit = 0;
int totalSum = 0;
String strUpperLimit;
int i;

strUpperLimit = JOptionPane.showInputDialog("You are about to sum the first N integers\nHow many would you like to sum?");

try
{

upperLimit = Integer.parseInt(strUpperLimit);

}

catch (NumberFormatException nfeInteger)
{

JOptionPane.showMessageDialog(null, "You need to enter an integer!", "Input Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);

}
// running the for loop
for (i=1; i <= upperLimit; i++)

// summing up each term into the overall sum
totalSum = totalSum + i;

JOptionPane.showMessageDialog(null, "The sum of the first " + upperLimit + " integers is " + totalSum, "Solution", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);

} // end main( )

} // 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.
  • the for loop
    • starts at one
    • ends at the user's inputted value for upperLimit
    • increments in ones
  • the totalSum term is incremented each time through the loop by the value of the counter in the for loop thus achieving our goal of
    totalSum = 1 + 2 + ... + upperLimit
    when the loop is completed

  • the showMessageDialog( ) method is used from the JOptionPane class to display the results while echoing the input

There isn't much else to say.