A Primer on Loops

Loops In Computing

All below is true of all loop constructs in computing. Some of them are a little more specialized, but the all forms of looping do the same thing. They all do this:

Do the statement or statements grouped below over and over while a certain condition exists.

So a loop will look like this:

while (some condition which is true, but can become false)
 { start of a group of statements
 statement
 statement
 end of the group of statements}
rest of program

Some examples of loops in English

  • “Keep driving around the block until you find a parking spot.”
  • “Run laps until while your heartrate is less than 144 beats per second.”
  • “Rock the cradle while the baby is awake.”
  • “Clap your hands together to stay warm while the temperature is below freezing.”

Loop Architecture

Loops in computer programs consist of 3 parts:

Initialization – this is where you set all your variables for the beginning of the loop. The condition which is tested to end the loop has to be set to a starting value. Any variables which are set in the loop usually have to be set to their starting values.

Loop Condition – the condition which is tested in order to terminate the loop.

Loop Body – the statements which are executed repeatedly until the Loop condition changes state.

Some standard loop constructs

Doing the loop body of statements a specified number of times.

Initialization
ctr = 0
max = 7
Loop Condition
while (ctr < max)
Loop Body
ctr = ctr + 1
. . . more statements

Discussion

This code fragment will execute the statements in the loop body max times. To change the number of times to execute the loop, change the value of max.

Note the statement “ctr = ctr + 1”. This statement adds 1 to the counter and store the result in ctr. It has the effect of increasing the value of ctr by 1 each time the loop is executed.

. . . rest of loop body

is executed the number of times specified in max.

Add a total variable to the above example

Initialization
ctr = 0
 max = 7
 dailytotal = 0
Loop Condition
while (ctr < max)
Loop Body
ctr = ctr + 1
get dailysales
dailytotal = dailytotal + dailysales

Each iteration of the loop gets a dailysales figure, perhaps from a single invoice, and adds it to the dailytotal variable. When the loop terminates, the dailytotal variable will contain the sum of the daily sales.

Doing something over and over while something is true

Initialization
condition = true
Loop Condition
while (condition)
Loop Body
series of statements

While this seems very simple, I add a caveat. The series of statements in the loop body must have the ability to set the condition to false. Otherwise the loop will never terminate.

A couple of real java programs

Here are two Java programs illustrating all this:

/*
 * This project displays two while loops implemented in Java
 * they are representative of most of the tasks you would be doing
 * in a Java class. Other forms of loops are available in 
 * Java - but they do not do anything that these loops don't do.
 */

package loopdemo;
import java.util.Scanner; // use to get keyboard input
import java.io.*;         // use to read from a file
/**
 *
 * @author Brian Gulino
 */
public class LoopDemo {

    /**
     * @param 
    */
    public static void main(String[] args) throws IOException{
        // a counter loop - use this construct when you need to 
        // execute a section of code a known number of times
        // let's say you want to print a number of asterisks on a line
        // you'll need these variables - first, naming conventions
        // "ast" will stand for asterisks - and all related variables 
        // will have "ast" in them
        Scanner keyboard = new Scanner(System.in);
        int ctrAst; // a counter - how many times you have excuted the loop
        int mxAst;  // maximum asterisks - how many time to execute the loop
        // initialization - do these before the loop starts
        System.out.print("\nhow many asterisks do you want to print: ");
        // ready to initialize our two loop variables
       mxAst = keyboard.nextInt();
       ctrAst = 0;
       // and here is the start of the loop
       while (ctrAst < mxAst){
           ctrAst = ctrAst + 1; //add one to the counter
           System.out.print('*'); // print a single asterisk
       }
        System.out.println("\nLoop is over");

    // here's the next loop construct - do this until a condition is 
    // satisfied. In this case, we will read a file with sales records and
    // total the sales until we run out of records.
    // open a file with sales figures on it 1 on each line.
    File file = new File("sales.txt");
    Scanner fileSales = new Scanner(file);
    int sales; // the sales figure for a single record
    int totSales; // the sum of the sales on all the records
    boolean recordsLeft; // keep reading records until this is false
    // initialize
    recordsLeft = true; // set to true or the loop won't run at all
    totSales = 0; // this is what will acccumulate the sales in the loop
    while (recordsLeft) { 
    recordsLeft = fileSales.hasNext();
    if (recordsLeft){
            // we have records in the file we will read one and add it to total
        sales=fileSales.nextInt(); // getting the next sales record
        totSales = totSales + sales; // and adding it to the total
    }
    }
    System.out.println("/nAnd the total sales are " + totSales);

}
}