|
|
|
The first (Factorial) example problem gives another illustration of a variable count pre-test loop using a "for" construct. The example also: (1) includes an error recovery mechanism using an "if-else" construct as illustrated previously, and (2) uses data items of type long (first time such data items are used in this sequence of WWW pages).
1. PROCESSING A LOOP "IN REVERSE" |
It is sometimes desirable to process a fixed count loop backwards, i.e. in reverse. In some programming languages (such as Ada and Pascal) this requires the inclusion of a reserved word such as reverse in the loop definition. In Java (and languages such as C and C++) this is not necessary because of the greater versatility of the for loop construct. All we need to do is decrement the loop parameter instead of the more usual incrementation. For example the code in Table 1 would produce the output:
10 9 8 7 6 5 4 3 2 1
// SEQUENCE NUMBERS CLASS // Frans Coenen // Tuesday 13 April 1999 // The University of Liverpool, UK class SequenceNumbers { // ------------------ METHODS ----------------------- /* Main method */ public static void main(String[] args) { final int START_CONDITION = 10; final int END_CONDITION = 0; // For loop for (int loopParameter = START_CONDITION;loopParameter > END_CONDITION; loopParameter--) System.out.print(loopParameter + " "); // End System.out.println("\n"); } } |
Table 1: Sequence of numbers output in "reverse"
3. EXAMPLE PROBLEM --- EXTENDED FACTORIAL APPLICATION3.1 RequirementsProduce a Java program that outputs the values of 1! to 20! inclusive. 3.2 AnalysisWe can make use of the Factorial class defined in the foregoing
section, we therefore only need an appropriate application class, (say)
FactiorialExtApp, which would only need one method (main).
Table 6: Implementation for factorial application
|
Created and maintained by Frans Coenen. Last updated 10 February 2015