INTRODUCTION TO PROGRAMMING IN JAVA: REPETITION ("DO WHILE", POST-TEST, LOOPS)

NOTE: This set of www pages is not the set of www pages for the curent version of COMP101. The pages are from a previous version that, at the request of students, I have kept on line.


CONTENTS

1. Post-test loops
2. The Java "do-while" loop construct
3. Example problem - Fibonacci
3.1. Requirements
 
3.2. Analysis
3.3. Design
3.4. Implementation
3.5. Testing



1. POST TEST LOOPS

Where as for a pre-test loop the control variable is tested prior to the start of each iteration in post-test loops the control variable is tested at the end of each iteration (Figure 1). From an efficiency point of view the often stated advantage is that we can reduce the number of tests (although only be 1!) of the loop control variable/parameter provided that we know that the loop must be exercised at least once. If there is a possibility that the loop should not be exercised at all then a post-test loop will not be appropriate (a pre-test loop will be required instead).

DISTINCTION BETWEEN PRE TEST AND POST TEST LOOPS

Figure 1: Distinction between pre-test and post-test loops




2. THE JAVA "DO-WHILE" LOOP CONSTRUCT

In Java a post test loop is implement using a "do-while" construct. This has the general form:

< START_EXPRESSION >

.....

do {
    < STATEMENTS TO BE REPEATED
    INCLUDING THE UPDATE_EXPRESSION >
    } while < TEST_EXPRESSION > ;

Note that the start expression is placed somewhere prior to the start of the construct, and that the update expression must be included in the body of the loop.

 

An example of the use of this construct is presented in Table 1 where a trivial piece of Java code is presented containing a post test variable count loop. On each iteration the user is asked to input an integer greater than 0 and less than 51. If a correct input is made the loop terminates. In Table 2 a second piece of Java code is presented which does exactly the same thing but using a while construct. Another example of the same problem is presented in Table 3 using a "for" construct. Note, in Tables 2 and 3 that these programs will test the number variable at least twice (as opposed to at least once using the do-while construct). Also we must initialise the number with an appropriate value to ensure that the user is allowed the opportunity to input a number.


// VARIABLE COUNT DO WHILE LOOP EXAMPLE APPLICATION
// Frans Coenen
// Wednesday 5 May 1999
// Revised: Wednesday 23 August 2005
// The University of Liverpool, UK
   
import java.util.*;

class DoWhileExample { 

    // ------------------- FIELDS ------------------------ 
        
    // Create Scanner class instance
    public static Scanner input = new Scanner(System.in);
    
    // ------------------ METHODDS -----------------------
    
    /* Main method  */

    public static void main(String[] args) {	
        int number;
	final int MAXIMUM = 50;
	final int MINIMUM = 1;
	
	// Invitation to input	
	System.out.print("Input an integer between " + MINIMUM + 
				" and " + MAXIMUM + " (inclusive): ");
	
	// Do-while loop	
	do {
	    number = input.nextInt();
	    } while (number < MINIMUM || number > MAXIMUM);
	
	// End
	
	System.out.println("Input = " + number);
	}

Table 1: Variable count "do-while" loop example

// VARIABLE COUNT WHILE LOOP EXAMPLE APPLICATION
// Frans Coenen
// Wednesday 5 May 1999
// Revised: Wednesday 23 August 2005
// The University of Liverpool, UK
   
import java.util.*;

class WhileLoopExample { 

    // ------------------- FIELDS ------------------------ 
        
    // Create Scanner class instance
    public static Scanner input = new Scanner(System.in);
    
    // ------------------ METHODDS -----------------------
    
    /* Main method  */

    public static void main(String[] args) {	
        int number = 0;
	final int MAXIMUM = 50;
	final int MINIMUM = 1;
	
	// Invitation to input	
	System.out.print("Input an integer between " + MINIMUM + 
				" and " + MAXIMUM + " (inclusive): ");
	
	// Do-while loop	
	while (number < MINIMUM || number > MAXIMUM) {
	    number = input.nextInt();
	    } 
	
	// End
	
	System.out.println("Input = " + number);
	}
    }

Table 2: Variable count "while" loop example

// VARIABLE COUNT FOR LOOP EXAMPLE APPLICATION
// Frans Coenen
// Friday 12 November 1999
// Revised: Wednesday 23 August 2005
// The University of Liverpool, UK
   
import java.util.*;
   
class ForLoopExample { 

    // ------------------- FIELDS ------------------------ 
        
    // Create Scanner class instance
    public static Scanner input = new Scanner(System.in);
    
    // ------------------ METHODDS -----------------------
    
    /* Main method  */

    public static void main(String[] args) {	
        int number = 0;
	final int MAXIMUM = 50;
	final int MINIMUM = 1;
	
	// Invitation to input	
	System.out.print("Input an integer between " + MINIMUM + 
				" and " + MAXIMUM + " (inclusive)");

	// For loop
	for (number=0;number < MINIMUM || number > MAXIMUM; ) {
	    number = input.nextInt();
	    } 
	
	// End
	
	System.out.println("Input = " + number);
	}
    }

Table 3: Variable count "for" loop example

The three pieces of code presented in Tables 1, 2 and 3 above all do the same thing, they allow the user to input a number within a certain range. This is a frequent requirement, however, we would prefer the code to be written in such a way that an error message is displayed whenever an incorrect input is detected. The code presented in Table 4 achieves this. Note that we are using a continuous do-while loop which, in the event of a correct input, we can "break out of" using a break statement.

// VARIABLE COUNT DO WHILE LOOP EXAMPLE APPLICATION VERSION 2
// Frans Coenen
// Wednesday 5 May 1999
// Revised: Thursday 1 September 2000, Wednesday 23 August 2005
// The University of Liverpool, UK
   
import java.util.*;

class DoWhileExampleVer2 { 

    // ------------------- FIELDS ------------------------ 
        
    // Create Scanner class instance
    public static Scanner input = new Scanner(System.in);
    
    // ------------------ METHODDS -----------------------
    
    /* Main method  */

    public static void main(String[] args) {	
        int number;
	final int MAXIMUM = 50;
	final int MINIMUM = 1;

        // Invitation to input

        System.out.print("Input an integer between " + MINIMUM + 
				" and " + MAXIMUM + " (inclusive): ");

        // Do-while loop

        do {
            number = input.nextInt();
	    if (number >= MINIMUM && number <= MAXIMUM) break;
	    else System.out.println("ERROR: given input (" + number + 
	    	") not within range " + MINIMUM + ".." + MAXIMUM + ", try again");
            } while (true);

        // End

        System.out.println("Input = " + number);
        }
    }

Table 4: Variable count "do-while" loop example with error message

In Tables 1 and 4 above variable count "do-while" loop examples were presented. "Do-while" loops can equally well be used to describe fixed count loops. In Table 5 we present the "smiley faces" program presented previously (using both a fixed count "for" and a fixed count a "while" loop), but in this case implemented using a fixed count "do-while" loop. Note that the test expression, unlike in the previous examples, includes the <= operator so that the same number of smiley faces are output as before. The distinction is that, as this is a post test loop, the loop parameter is incremented before we get to the test expression. Thus if we had not altered the test expression only 9 smiley faces would have been produced instead of 10!

// FIXED COUNT DO-WHILE EXAMPLE APPLICATION
// SMILEY FACES 3
// Frans Coenen
// Friday 12 November 1999
// The University of Liverpool, UK
   
class SmileyFace {
 
    // ------------------ METHODS -----------------------
    
    /* Main method  */

    public static void main(String[] args) {	
        int       loopParameter;
	final int START_CONDITION = 0;
	final int END_CONDITION   = 10;
	
	// Do-while loop
	
	loopParameter = START_CONDITION;
	do {
	    System.out.print("(-:\t");
	    loopParameter++;
	    } while (loopParameter <= END_CONDITION)
		
	// End
	
	System.out.println("\n");
	}
    }

Table 5: Fixed count "do-while" loop example (smiley faces 3)



3. EXAMPLE PROBLEM - FIBONACCI


2.1 Requirements

Design and Produce some software, written in Java, that outputs the first N terms of the Fibonacci Sequence:

0, 1, 1, 2, 3, 5, 8, 13 ....

Where N is an integer in the range 0..45 inclusive (where the 0th term represents the first term in the sequence, i.e 0).

Note that the first two terms in the sequence are 0 and 1, and each term thereafter is the sum of the two proceeding terms. Thus:

fib(N) = fib(N-1) + fib(N-2)

where N is greater than 2.

FIBONACCI'S RABBITS

Figure 2: Fibonacci's rabbits


3.2 Analysis

Since it is likely that there will be more occasions that we wish to compute a Fibonacci sequence we will create a separate class Fibonacci which we will then couple to an appropriately defined application class. A class diagram for the intended software system is presented in Figure 3.

CLASS DIAGRAM FOR FIBONACCI PROBLEM

Figure 3: Class diagram for the Fibonacci problem


3.3 Design

From Figure 3 the design comprises two classes, Fiobonacci and FibonacciApp.

Field Summary
private int numberOfTerms
           A private instance field describing the number of terms in the proposed Fibonacci sequence.

Constructor Summary
Fibonacci(int numTerms)
           Constructs to create an instance of the class Fibonacci given a required number of terms as input.

Method Summary
public void calcFibonacciSequence()
           Method to calculate and output the Fibonacci sequence from 1 to the given number of terms. Uses a "do-while" loop within which there is a nested if-else statement to deal with the special cases for the first two terms.

A Nassi-Shneiderman design for the above is presented in Figure 4. Note how a post test loop is indicated by such a chart.

FIBONACCI CLASS N-S DIAGRAM

Figure 4: Nassi-Shneiderman chart for Fibonacci class


3.3.2 FibonacciApp Class

Field Summary
public static Scanner keyboardInput
           A class instance to facilitate input from the input stream.

Method Summary
public static void main(String[] args)
           Main method to produce the required Fibonacci sequence. Calls input to allow the user to input a required number of terms. Once the required number of terms has been obtained an instance of the class Fibonacci is created and the terms output through a call to the calcFibonacciSeq class method.
private static int input()
           Method that allows the user to input a required number of terms. This must be an integer ranging from 0 to 45. The method contains an error checking mechanism, using a "do-while" loop, to check the input and to give the user the opportunity to re-input the required number of terms in the event of the detection of an inappropriate value.

Two Nassi-Shneiderman charts for the above are given in Figure 5.


3.4 Implementation


3.4.1 Fibonacci class

FIBONACCI APPLICATIONH CLASS N-S DIAGRAM

Figure 5: Nassi-Shneiderman chart for FibonacciApp class

// FIBONACCI CLASS
// Frans Coenen
// Wednesday 5 May 1999
// The University of Liverpool, UK

class Fibonacci {

    // ------------------ FIELDS ----------------------
    
    private int numberOfTerms;
    
    // ----------------- CONSTRUCTORS -----------------
    
    /* Fibonacci constructor */
    
    public Fibonacci(int numTerms) {
    	 numberOfTerms = numTerms;
	 }
	
    // ------------------ METHODS ---------------------
    
    /* Calculate and output Fibonacci sequence */
    
    public void calcFibonacciSeq() {
	int loopCounter = 0;
        int fib1        = 0;
	int fib2        = 1;
	int tempTerm;
	
	do {	
	    if (loopCounter == 0) System.out.print(fib1 + " ");
	    else if (loopCounter == 1) System.out.print(fib2 + " ");
	    else {
		tempTerm = fib1 + fib2;
		fib1 = fib2;
		fib2 = tempTerm;
		System.out.print(fib2 + " ");   
		}	
            loopCounter++;		     
	    } while (loopCounter <= numberOfTerms);
	    
	// End
	
	System.out.println(); 	
	}
    }

Table 6: Source code for Fibonacci class

Instead of the if-else selection statement contained within the do-while loop in the calcFibonacciSeq method we could have used a case statement as shown below. A Nassi-Schneiderman chart for this alternative implementation of the calcFibonacciSeq method is given in Figure 6.

do {	
    switch (loopCounter) {		
	case 0:
	    System.out.print(fib1 + " ");
	    break;
	case 1:    	
	    System.out.print(fib2 + " ");
	    break;
	default:
	    tempTerm = fib1 + fib2;
	    fib1 = fib2;
	    fib2 = tempTerm;
	    System.out.print(fib2 + " ");   
	    }	
        loopCounter++;		     
	} while (loopCounter <= numberOfTerms);  
FIBONACCI CLASS N-S DIAGRAM (ALTERNATIVE IMPLEMENMTATION)

Figure 6: Nassi-Shneiderman chart for FibonacciApp class (alternative implementation)


3.4.2 FibonacciApp class

// FIBONACCI APPLICATION CLASS
// Frans Coenen
// Wednesday 5 May 1999
// Revised: Wednesday 23 August 2005
// The University of Liverpool, UK
   
import java.util.*;
   
class FibonacciApp { 
  
    // ------------------- FIELDS ------------------------ 
                      
    // Create Scanner class instance
    public static Scanner keyboardInput = new Scanner(System.in);
     
    // ------------------ METHODDS -----------------------
    
    /* Main method  */

    public static void main(String[] args) {
    	int numTerms;
	final int MAX_TERMS = 45;
	final int MIN_TERMS = 0;
	
	// Input number of terms	
	numTerms = input();
		
	// Create instance of class Fibonacci	
	Fibonacci newFibonacci = new Fibonacci(numTerms);
	
	// Calculate	
	newFibonacci.calcFibonacciSeq();
        }
	
    /* Input method  */

    private static int input()  {
        int number;
	final int MAXIMUM = 45;
	final int MINIMUM = 0;

        // Invitation to input
        System.out.println("Input Number of terms (int " + MINIMUM + 
				" and " + MAXIMUM + " inclusive): ");

        // Do-while loop
        do {
            number = keyboardInput.nextInt();
	    if (number >= MINIMUM && number <= MAXIMUM) break;
	    else System.out.println("ERROR: given input (" + number + 
	    	") not within range " + MINIMUM + ".." + MAXIMUM + ", try again");
            } while (true);

        // Return
        return(number);
        }	
    }

Table 7: Source code for fibonacci application class

Note:

  • Input is of the form illustrated in Table 4.

3.5 Testing

We have two loops one in the main method and one in the calcFibonacciSeq method. The first has two paths within it and the second three. Thus both loop and path testing, supported by some arithmetic and limit testing, and BVA, should be carried out. We will consider the two methods individually.

To test the main method we should include test cases to exercise the loop for:

One iteration
Two iterations

We should also test the Boolean expression used to test the loop parameter so that we include inputs of less than 0, greater than 45 and somewhere within the range. With respect to arithmetic testing we should test a 0 value and some positive value. Limit testing will require that we include test cases at the limits and BVA that we include test cases just inside and outside the limits.

A similar set of considerations are applicable to the calcFibonacciSeq method. An appropriate set of test cases is presented in the table (right).

TEST CASERESULT
numTermsOUTPUT
-1Second chance
00
10 1
200 1 1 2 3 5 8 13 21 34 55 89 ...
440 1 1 2 3 5 8 13 21 34 55 89 ...
450 1 1 2 3 5 8 13 21 34 55 89 ...
46Second chance

Some sample output is given in Table 8

$ java FibonacciApp
Input Number of terms (int 0 and 45 (inclusive):
-1
ERROR: given input (-1) not within range 0..45, try again
0
0

$ java FibonacciApp
Input Number of terms (int 0 and 45 inclusive):
46 
ERROR: given input (46) not within range 0..45, try again
45
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 
4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 
514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 
24157817 39088169 63245986 102334155 165580141 267914296
433494437 701408733 1134903170

$ java FibonacciApp
Input Number of terms (int 0 and 45 inclusive):
1
0 1

$ java FibonacciApp
44
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 
6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 
832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 
39088169 63245986 102334155 165580141 267914296 433494437 
701408733

$ java FibonacciApp
Input Number of terms (int 0 and 45 inclusive):
20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Table 8: Sample output




Created and maintained by Frans Coenen. Last updated 10 February 2015