1 // Example 3.2 joi/examples/ForDemo.java 2 // 3 // 4 // Copyright 2003 Bill Campbell and Ethan Bolker 5 6 // A class illustrating the For-statement. A typical run: 7 // 8 // %> java ForDemo 9 // Enter integer: 7 10 // 7 integers starting at 0: 0 1 2 3 4 5 6 11 // First 7 Fibonacci numbers (for): 1 1 2 3 5 8 13 12 // First 7 Fibonacci numbers (while): 1 1 2 3 5 8 13 13 // 49 @'s: 14 // @@@@@@@ 15 // @@@@@@@ 16 // @@@@@@@ 17 // @@@@@@@ 18 // @@@@@@@ 19 // @@@@@@@ 20 // @@@@@@@ 21 22 public class ForDemo 23 { 24 public static void main( String[] args ) 25 { 26 Terminal terminal = new Terminal(); // for input and output 27 28 // Prompt for and read a single integer. 29 int n = terminal.readInt( "Enter integer:" ); 30 31 terminal.print( n + " integers starting at 0:" ); 32 for ( int i = 0; i < n; i++ ) { 33 terminal.print( " " + i ); // all one one line 34 } 35 terminal.println(); // the newline 36 37 // Build Fibonacci numbers 1, 1, 2, 3, 5, 8, 38 // by adding last two together to make the next 39 // Use three int variables and a loop: 40 41 int thisOne, lastOne, nextOne; 42 terminal.println( "First " + n + " Fibonacci numbers:" ); 43 44 terminal.print("(for): " ); 45 thisOne = 1; 46 lastOne = 1; 47 for ( int i = 1; i <= n; i++ ) { 48 terminal.print( " " + lastOne ); 49 nextOne = thisOne + lastOne; 50 lastOne = thisOne; 51 thisOne = nextOne; 52 } 53 terminal.println(); 54 55 // Since i is never used in the body of the previous loop 56 // we can count down to get the same output: 57 terminal.print("(for, counting down):" ); 58 thisOne = 1; 59 lastOne = 1; 60 for ( int counter = n; counter > 0; counter-- ) { 61 terminal.print( " " + lastOne ); 62 nextOne = thisOne + lastOne; 63 lastOne = thisOne; 64 thisOne = nextOne; 65 } 66 terminal.println(); 67 68 // Replace the for loop with a while loop 69 terminal.print("(while): " ); 70 thisOne = 1; 71 lastOne = 1; 72 int i = 1; 73 while ( i <= n ) { 74 terminal.print( " " + lastOne ); 75 nextOne = thisOne + lastOne; 76 lastOne = thisOne; 77 thisOne = nextOne; 78 i++; 79 } 80 terminal.println(); 81 82 terminal.println("Nested for loops: " + (n*n) + " @'s:" ); 83 for ( int row = 1; row <= n ; row++ ) { 84 for ( int col = 1; col <= n; col++ ) { 85 terminal.print( " @" ); 86 } 87 terminal.println(); 88 } 89 } 90 }