/**
* Demonstrate arrays
*
* @author (Michael Branicky), 10/05/06, 10/02/07
*/
public class ArraysDemo {
   public static void main(String args[]) {
     int day, i; 

     double temp [] = { 17.3, 19.5, 23.3, 25.3 };
     System.out.print("temp: ");
     for (day=0; day<temp.length; day++) {
       System.out.print(temp[day]+" ");
     }
     System.out.println();
     
     // Moving Average / Smoothing
     double smoothedAvg [] = new double [temp.length];
     smoothedAvg[0] = temp[0];
     for (day=1; day<temp.length; day++) {
       smoothedAvg[day] = 0.5*(temp[day-1]+temp[day]);
     }
     System.out.print("smoothed temp: ");
     for (day=0; day<smoothedAvg.length; day++) {
       System.out.print(smoothedAvg[day]+" ");
     }
     System.out.println();


     // populate an array that stores whether 2 through 100 are prime or not
     boolean primality [] = new boolean [99];
     for (i=2; i<=100; i++) {
       primality[i-2] = isPrime(i);
     }
     // an equivalent piece of code
     for (i=0; i<99; i++) {
       primality[i] = isPrime(i+2);
     }

     // print out the answer as 0's and 1's
     System.out.print("primality: ");
     for (i=0; i<99; i++) {
       if(primality[i]) {
         System.out.print(1);
       }
       else {
         System.out.print(0);
       }
     }
     System.out.println();


     // Test of array references and array passing
     int grades [] = { 93, 71, 85 };
     int grades2 [];

     // print grades
     System.out.print("grades: ");
     for (i=0; i<grades.length; i++) {
       System.out.print(grades[i]+" ");
     }
     System.out.println();

     grades2 = grades;
     System.out.println("length of grades2: "+grades2.length);
     // print grades2
     System.out.print("grades2: ");
     for (i=0; i<grades2.length; i++) {
       System.out.print(grades2[i]+" ");
     }
     System.out.println();

     grades2[1] = 74;
     // print grades
     System.out.print("grades: ");
     for (i=0; i<grades.length; i++) {
       System.out.print(grades[i]+" ");
     }
     System.out.println();

     changeElt(grades);
     // print grades
     System.out.print("grades: ");
     for (i=0; i<grades.length; i++) {
       System.out.print(grades[i]+" ");
     }
     System.out.println();
  }


  public static void changeElt (int arr []) {
    arr[2] = 84;
  }

  // returns true if n>=2 is prime; false, otherwise
  public static boolean isPrime (int n) {
    int i;

    if (n < 2) { 
      return false;
    }  // prime must be >=2
    i = 2;
    // test factors up to, and including, the square root of n
    while (i*i <= n) {
      // if i evenly divides n, n isn't prime
      if (n%i == 0) {
        return false;
      }
      i = i + 1;
    }
    return true;
  } 
}
