1 // Example 4.2 joi/examples/ArrayDemo.java 2 // 3 // 4 // Copyright 2003 Bill Campbell and Ethan Bolker 5 6 // A class illustrating arrays 7 // 8 // Build an array of Fibonacci numbers 1, 1, 2, 3, 5, 8, ... 9 // and play with it. Sample output: 10 // 11 // %> java ArrayDemo 8 12 // Sum first 8 Fibonacci numbers 13 // 1 1 2 3 5 8 13 21 14 // total: 54 15 // 16 // First 8 Fibonacci numbers (reverse order) 17 // 21 13 8 5 3 2 1 1 18 // Every other fib 19 // 1 1 20 // 3 2 21 // 5 5 22 // 7 13 23 24 public class ArrayDemo 25 { 26 public static void main( String[] args ) 27 { 28 int n = 6; // default 29 if (args.length > 0) { 30 n = Integer.parseInt(args[0]); 31 } 32 33 int[] fibs = new int[n]; // declare and create array 34 35 fibs[0] = fibs[1] = 1; // fill first two positions 36 for ( int i = 2; i < n; i++ ) { // fill the rest 37 fibs[i] = fibs[i-1] + fibs[i-2]; 38 } 39 40 // standard idiom for accumulating total of an array 41 int total = 0; 42 System.out.println("Sum first " + n + " Fibonacci numbers"); 43 for ( int i = 0; i < n; i++ ) { 44 System.out.print(fibs[i] + " "); 45 total += fibs[i]; 46 } 47 System.out.println("\ntotal: " + total); 48 System.out.println(); 49 50 System.out. 51 println("First " + n + " Fibonacci numbers (reverse order)"); 52 for ( int i = n-1; i >= 0 ; i-- ) { 53 System.out.print(fibs[i] + " "); 54 } 55 System.out.println(); 56 57 System.out.println("Every other fib"); 58 for ( int i = 0; i < n ; i += 2 ) { 59 System.out.println((i+1) + "\t" + fibs[i]); 60 } 61 System.out.println(); 62 } 63 }