;; Caltech CS 1 Fall 2007
;; Java code used in Lecture 20 (12/05/07)
;; mvanier@cs.caltech.edu    page 1 of 2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

// Java function to sum integers:
public int sum (int n) {
  if (n == 0)
    return (0);
  else 
    return (n + sum(n - 1));
}

// Evaluate a quadratic equation, in Java:
int aquad(int a, int b, int c, int x) {
     int res = 0;
     res = res + c;
     res = res + b * x;
     res = res + a * x * x;
     return (res);
}

// Finding the maximum of two values in Java:
int max (int a, int b) {
   int res;
   if (a > b)
      res = a;
   else
      res = b;
   return (res);
}

// Returning from inside a function in Java:
int scalebc(int a, int b, int c) {
     int LARGE = 1000000000;    // for instance...
     if (b == 0) return(LARGE); // avoid division by 0
     if (c == 0) return(LARGE); // similarly
     return (a / (b * c));      // return an int
}

// for loop in Java:
int sum(n) {
   int res = 0;
   int i;
   for (i = 0; i <= n; i = i + 1)
       res = res + i;
   return(res);
}

// for loop, with some shortcuts:
int sum(n) {
   int res = 0;
   int i;
   for (i = 0; i <= n; i++) // i++ is same as: i = i + 1
       res += i; // same as: res = res + i;
   return(res);
}

;; Caltech CS 1 Fall 2007
;; Java code used in Lecture 20 (12/05/07)
;; mvanier@cs.caltech.edu    page 2 of 2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

// Complex number class:
class Complex {
    private int realVal = 0;
    private int imagVal = 0;

    public Complex(int real, int imag) {
        realVal = real;
        imagVal = imag;
    }

    public int getReal() {
        return(realVal);
    }

    public int getImag() {
        return(imagVal);
    }
    
    // "add" (add two complex numbers) as a method
    public Complex add(Complex other) {
	return(new Complex
	  (realVal + other.getReal()),
	  (imagVal + other.getImag()));
    }
}


// "addf" (add two complex numbers) as a function
public Complex addf(Complex other) {
    return(new Complex
        (realVal + other.getReal()),
        (imagVal + other.getImag()));
}

// Defining complex numbers:
Complex a = new Complex(1, 3.4);
Complex b = new Complex(-5, 25);
// Use of "add" method:
Complex c = a.add(b);
// Use of "addf" function:
Complex d = addf(a, b);


