Computer Science 15-110, Spring 2010
Class Notes:  Getting Started with One-Dimensional Arrays

In class this week we are starting to use one-dimensional arrays.  Here is the sample code we developed in class (warts and all) to demonstrate the ideas:

```// ArrayDemo.java
// Developed in class to demonstrate the use of one-dimensional arrays.

import java.util.Scanner;
import java.util.Arrays;
class ArrayDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter n: ");
int n = scanner.nextInt();
int[] a = new int[n];
System.out.println("Now enter " + n + " + ints:");
for (int i=0; i<n; i++) {
System.out.print("  Enter int #" + i + ": ");
a[i] = scanner.nextInt();
}```
```    System.out.println("\nArray, term-by-term:");
for (int i=0; i<n; i++)
System.out.println(a[i]);
```
```    System.out.println("\nEntire array:");
System.out.println(Arrays.toString(a));
```
```    // once more, but with Fractions
System.out.println("Once more, but with Fractions...");
System.out.print("Enter n: ");
n = scanner.nextInt();
Fraction[] b = new Fraction[n];
System.out.println("Now enter " + n + " + Fractions:");
for (int i=0; i<n; i++) {
System.out.print("  Enter num-space-den #" + i + ": ");
int num = scanner.nextInt();
int den = scanner.nextInt();
b[i] = new Fraction(num, den);
}```
```    System.out.println("\nArray, term-by-term:");
for (int i=0; i<n; i++)
System.out.println(b[i]);
```
```    System.out.println("\nEntire array:");
System.out.println(Arrays.toString(b));
```
```  }
}```
```class Fraction {
// instance variables (the data for each instance)
private int num, den;
```
```  // accessors ("getters")
public int getNum() { return this.num; }
public int getDen() { return this.den; }
```
```  // mutators ("setters")
// bad idea for Fraction class, but included here
// for demonstrational purposes.
public void setNum(int num) {
this.num = num;
reduce();
}

```
```  public Fraction times(Fraction that) {
int num = this.num * that.num;
int den = this.den * that.den;
Fraction result = new Fraction(num, den);
return result;
}
```
```  public String toString() {
if (this.den == 1)
return ""+this.num;
return this.num + "/" + this.den;
}
```
```  //  public static Fraction constructor(int num, int den) {
public Fraction(int num, int den) {
this.num = num;
this.den = den;
reduce();
}
```
```  private void reduce() {
if (this.den == 0) return;
int gcd = gcd(this.num, this.den);
this.num /= gcd;
this.den /= gcd;
}
```
```  private static int gcd(int x, int y) {
// gcd(x,y) == gcd(y,x%y)
while (y != 0) {
int r = x%y;
x = y;
y = r;
}
return x;
}
}```

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem