INTRODUCTION TO PROGRAMMING IN JAVA: REPETITION AND NESTED 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. Overview
2. Example problem - Multiplication table
2.1. Requirements
2.2. Analysis
 
2.3. Design
2.4. Implementation
2.5. Testing
3. Alternative implementation

The random number generator example problem uses all three loop constructs in a variety of variable and fixed count modes.




1. OVERVIEW

As with selection statements loops can be nested. Care should be taken when nesting loops as this tends to decreases the readability of the code. Unless we are undertaking some fairly trivial nesting it is normally better to encode the nested loops in the form of further methods called from within the "parent" loop.



2. EXAMPLE PROBLEM - MULTIPLICATION TABLE


2.1 Requirements

Produce a Java program that outputs a 12x12 table such that the intersections of coordinates represent the product of the coordinates, i.e. a 12x12 multiplication table.


2.2 Analysis

This is a fairly trivial application therefore we will implement the solution using a simple application program comprising only a main method and a supporting method to output a horizontal line.


2.3 Design

Method Summary
public static void main(String[] args)
           Main method to produce the required multiplication table. Includes a call to a second method that draws a horizontal line. Main method performs the following sequence of operations:
  1. Draw horizontal line (call to outputHorizontalLine method).
  2. For loop to output "X" coordinates (column numbers).
  3. Draw horizontal line (call to outputHorizontalLine method).
  4. Two for loops, one nested inside the other to output the table.
  5. Draw horizontal line (call to outputHorizontalLine method).
private static void outputHorizontalLine()
           Trivial method to output a line of '-' characters.

NASSI-SHNEIDERMAN CHART FOR MULTIPLICATION TABLE GENERATION
	VERSION 1

Figure 2: Nassi-Shneiderman charts for multiplication table generator (Version 1)


2.4. Implementation

The encoding of the above design is as follows:

// MULTIPLICATION TABLE
// Frans Coenen
// Thursday 13 June 1999
// The University of Liverpool, UK
   
class MultiplicationTable { 

    // ------------------ METHODS -----------------------
    
    /* Main method  */

    public static void main(String[] args) {	
        int       columnNumber, rowNumber;
	final int START_CONDITION = 1;
	final int END_CONDITION   = 13;
	
	// Horizontal line
	
	System.out.println("\n");
	outputHorizontalLine();
	
	// Output top line of "coordinates" (Column numbers)
	
	System.out.print("\t| ");
	for(columnNumber=START_CONDITION;columnNumber < END_CONDITION; 
						columnNumber++) {
	    System.out.print(columnNumber + "\t ");
	    }
		
	// Horizontal line
	
	System.out.print("\n");
	outputHorizontalLine();
	
	// Output table entries
	
	for(rowNumber = START_CONDITION; rowNumber < END_CONDITION; 
							rowNumber++) {
	    System.out.print(" " + rowNumber + "\t| ");
	    for(columnNumber = START_CONDITION; columnNumber < END_CONDITION; 
	    						columnNumber++) {
	        System.out.print(columnNumber*rowNumber + "\t ");
		}
	    System.out.print("\n");		
	    }
	
	// Horizontal line
	
	outputHorizontalLine();
	System.out.println("\n");
	}
	
    /* Draw horizontal line method */	
     
    private static void	outputHorizontalLine() {
        System.out.println("--------+-----------------------------------" +
	      "---------------------------------------------------------");
        }
    }

Table 1: Multiplication table generation program (Version 1)


2.5 Testing

The code cannot be influenced by a user therefore a simple run through will be appropriate. The result will be of the form shown below.

$ java MultiplicationTable


----+-----------------------------------------------------------------------
    | 1    2     3     4     5     6     7     8     9     10    11    12
----+-----------------------------------------------------------------------
 1  | 1    2     3     4     5     6     7     8     9     10    11    12
 2  | 2    4     6     8     10    12    14    16    18    20    22    24
 3  | 3    6     9     12    15    18    21    24    27    30    33    36
 4  | 4    8     12    16    20    24    28    32    36    40    44    48
 5  | 5    10    15    20    25    30    35    40    45    50    55    60
 6  | 6    12    18    24    30    36    42    48    54    60    66    72
 7  | 7    14    21    28    35    42    49    56    63    70    77    84
 8  | 8    16    24    32    40    48    56    64    72    80    88    96
 9  | 9    18    27    36    45    54    63    72    81    90    99    108
 10 | 10   20    30    40    50    60    70    80    90    100   110   120
 11 | 11   22    33    44    55    66    77    88    99    110   121   132
 12 | 12   24    36    48    60    72    84    96    108   120   132   144
----+----------------------------------------------------------------------- 



3. ALTERNATIVE IMPLEMENTATION (WITHOUT NESTED LOOPS)

An alternative implementation might comprise four distinct methods: main, outputTopLine, outputTableRow and outputHorizontalLine. The advantage is that we avoid the loop nesting and make the main method less cluttered, therefore more readable and thus more maintainable. A class diagram for this proposed alternative implementation is presented in Figure 3.

 
CLASS DIAGRAM FOR MULTIPLICATION TABLE GENERATION PROGRAM 
	(VERSION 2)

Figure 3: Class diagram for multiplication table program (Version 2)

Field Summary
private static final int START_CONDITION
           A ptrivate class constant, set to 1, marking the start value for the loop counter.
private static final int END_CONDITION
           A ptrivate class constant, set to 13, marking the end value for the loop counter.

Method Summary
public static void main(String[] args)
           Main method. Calls outputTopLine method, then loops through row number calling outputTableRow method on each iteration. On completion of loop calls outputHorizontalLine method.
private static void outputTopLine()
           Outputs start of table: horizontal line, list of column numbers (using a loop construct) and another horizontal line.
private static void outputTableRow(int rowNum)
           Outputs elements in row of table using a loop construct. On each iteration the product of the current row and column numbers is output.
private static void outputHorizontalLine()
           Trivial method to output a line of '-' (hyphen) characters.

Appropriate Nassi-Shneiderman charts for the first three of the above methods are presented in Figure 4.


NASSI-SHNEIDERMAN CHART FOR MULTIPLICATION TABLE GENERATION
	(VERSION 2a) NASSI-SHNEIDERMAN CHART FOR MULTIPLICATION TABLE GENERATION
	(VERSION 2b)

Figure 4: Nassi-Shneiderman charts for multiplication table generator (Version 2)

The implementation is as given in Table 2.

// MULTIPLICATION TABLE VERSION 2
// Frans Coenen
// Thursday 17 May 1999
// The University of Liverpool, UK
   
class MultiplicationTableVer2 { 

    // ------------------- FIELDS ------------------------
    
    private static final int startCondition = 1;
    private static final int endCondition   = 13;
    
    // ------------------ METHODDS -----------------------
    
    /** Main method  */

    public static void main(String[] args) {	
        int rowNumber;
	
	// Output top line of table
	
	outputTopLine();

	// Output table entries
	
	for(rowNumber = startCondition; rowNumber < endCondition; 
			rowNumber++) {
	    outputTableRow(rowNumber);			
	    }
	
	// Horizontal line
	
	outputHorizontalLine();
	System.out.println("\n");
	}

    /* Method to output top line of table. */
    	
    private static void outputTopLine() {
        int columnNumber;
	
	// Horizontal line
	
	System.out.println("\n");
	outputHorizontalLine();
	
	// Output top line of "coordinates"
	
	System.out.print("\t| ");
	for(columnNumber = startCondition; columnNumber < endCondition; 
			columnNumber++) {
	    System.out.print(columnNumber + "\t ");
	    }
	    
	// Horizontal line
	
	System.out.print("\n");
	outputHorizontalLine(); 
	}

    /* Method to output table row */
    	
    private static void outputTableRow(int rowNum) {
    	int columnNumber;
	
	// Row number
	
	System.out.print(" " + rowNum + "\t| ");
	
	// Entries
	
	for(columnNumber = startCondition; columnNumber < endCondition; 
	    		columnNumber++) {
	    System.out.print(columnNumber*rowNum + "\t ");
	    }
	
	// End
	
	System.out.print("\n");	    
        }
	   	
    /* Output horizontal line */	
     
    private static void	outputHorizontalLine() {
        System.out.println("--------+-------------------------------------" +
			"---------------------------------------------------" +
			"----");
        }
    }

Table 2: Multiplication table generation program (Version 2)




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