Lab 09 Solution
Version 1

 


Problem 01

  Modify the program ArrayGrades to use an input correction loop so that it will only accept grades in the range 0 to 100 (inclusive), prompting the user to re-enter if they supply a grade out of range.
Click Here To Run This Program On Its Own Page
// Program: LAB09PR01
// Author:  Joshua S. Hodas
// Date:    October 31, 1998
// Purpose: Modify ArrayGrades to require good input.
 
import HMC.HMCSupport;
 
class LAB09PR01 {
 
    public static void main(String args[]) {
 
        int numGrades;
        double grades[];
        double sum = 0, average;
 
        // Prompt the user for the number of grades to be used.
 
        HMCSupport.out.print("How many grades do you want to average? ");
        numGrades = HMCSupport.in.nextInt();
 
        // Allocate the grade array, now that we know how many grades.
 
        grades = new double[numGrades];
 
        // Input the grades, and add them up.
 
        sum = 0;
        for (int i = 0 ; i < numGrades ; i++) {
 
            // Added prompt to encourage entering one grade at a time.
            HMCSupport.out.print("Please enter grade #" + (i+1) + ": ");
            grades[i] = HMCSupport.in.nextDouble();
 
            // Loop to insure correct input:
            while (grades[i] < 0 || grades[i] > 100) {
 
                HMCSupport.out.print("That grade was out of range.");
                HMCSupport.out.print(" Please re-enter it: ");
                grades[i] = HMCSupport.in.nextDouble();
            }
            sum += grades[i];
        }
        average = sum / numGrades;
 
        // Echo back the grades, and the average.
 
        HMCSupport.out.print("The average of ");
        for (int i = 0 ; i < numGrades ; i++) {
 
            // Print a comma before all but first grade.
 
            if (i != 0)
                HMCSupport.out.print(", ");
 
            HMCSupport.out.print(grades[i]);
        }
 
        HMCSupport.out.println(" is " + average);
    }
 
}

For each of the remaining problems we will show just the method that solves the problem. At the end we give a program that tests all the individual methods.


Problem 02

  Write a method which takes an array of doubles and returns the sum of the squares of the elements in the array.

    // Problem 02
 
    public static double sumOfSquares(double[] data) {
 
        double sum = 0.0;
 
        for (int i = 0; i < data.length ; i++) {
 
            sum += data[i] * data[i];
        }
        return sum;
    }


Problem 03

  Write a method which takes an array of doubles and returns the largest value in the array.

Make sure you do not make any assumptions about the possible range of values in the array. In particular, don't assume the numbers are all positive, and don't rely on knowing the value of the smallest possible java double value.

    // Problem 03
 
    public static double largestValue(double[] data) {
 
        double largest = data[0];  // Begin assuming 1st element
                                   // is largest.
        for (int i = 0; i < data.length ; i++) {
 
            if (data[i] > largest) { // If see bigger element
                                     // replace old largest
                largest = data[i];
            }
        }
        return largest;
    }


Problem 04

  Add to the last program a method which takes two arrays and computes and returns the sum of the squares of the placewise difference between the elements of the two arrays.

    // Problem 04
 
    public static double sumDiffSquare(double[] data1, double[] data2) {
 
        double sum = 0.0, diff;
 
        for (int i = 0; i < data1.length ; i++) {
 
            diff = data1[i] - data2[i];
            sum += diff * diff;
        }
        return sum;
    }


Problem 05

  Add a method that computes the dot-product of two vectors. Recall that for two n-dimensional vectors, A and B,
A.B = A1B1 + ... + AnBn

    // Problem 05
 
    public static double dotProduct(double[] a, double[] b) {
 
        double sum = 0.0;
 
        for (int i = 0; i < a.length ; i++) {
 
            sum += a[i] * b[i];
        }
        return sum;
    }


Problem 06

  Add a method that computes the length (or, magnitude), |A|, of a vector, A, which is the square root of the sum of the squares of the individual components. Note that you can compute the sum of the squares manually (using a loop), or note that it is the result of taking the dot product of the vector with itself.

    // Problem 06
 
    public static double magnitude(double[] vector) {
 
        return Math.sqrt(dotProduct(vector,vector));
    }


Problem 07

  Recall that for two n-dimensional vectors, A and B, the dot-product also satifies the equation:
A.B = |A||B|cos(theta)
where theta is the angle between the two vectors. Use this fact, the dot product method from the last problem, and the method Math.acos to write a method which, given two vectors, computes and returns the angle theta (in radians) between them.

    // Problem 07
 
    public static double angleBetween(double[] a, double[] b) {
 
        // Law of cosines says A . B = |A||B|cos(Theta)
 
        double
            aDotB = dotProduct(a,b),
            magA  = magnitude(a),
            magB  = magnitude(b),
            theta = Math.acos(aDotB/(magA*magB));
 
        return theta;
 
    }


Unified Solution:

 

Click Here To Run This Program On Its Own Page
// Program: LAB09
// Author:  Joshua S. Hodas
// Date:    October 31, 1998
// Purpose: Test solutions to Lab 09 problems 02 - 07
 

import HMC.HMCSupport; class LAB09 { public static void main(String args[]) { double[] a = {5.2,2,8.8,4,-1.3,10,-12.1}; double[] b = {3.2,-5.4,1.7,12.2,-11.1,4.5,3.0}; // Added 2nd array HMCSupport.out.println("The first array being tested:"); printArray(a); HMCSupport.out.print("The sum of the squares is: "); HMCSupport.out.println(sumOfSquares(a)); HMCSupport.out.print("The sum of the squares is: "); HMCSupport.out.println(sumOfSquares(a)); HMCSupport.out.print("The largest value is: "); HMCSupport.out.println(largestValue(a)); HMCSupport.out.println("The second array being tested:"); printArray(b); HMCSupport.out.print("The sum of the squares of the " + "placewise differences is: "); HMCSupport.out.println(sumDiffSquare(a,b)); HMCSupport.out.print("The dot product of the two is: "); HMCSupport.out.println(dotProduct(a,b)); HMCSupport.out.print("The magnitude of the first is: "); HMCSupport.out.println(magnitude(a)); HMCSupport.out.print("The magnitude of the second is: "); HMCSupport.out.println(magnitude(b)); HMCSupport.out.print("The angle between them is: "); HMCSupport.out.println(angleBetween(a,b));

}

// Problem 02 public static double sumOfSquares(double[] data) { double sum = 0.0; for (int i = 0; i < data.length ; i++) { sum += data[i] * data[i]; } return sum; }

// Problem 03 public static double largestValue(double[] data) { double largest = data[0]; // Begin assuming 1st element // is largest. for (int i = 0; i < data.length ; i++) { if (data[i] > largest) { // If see bigger element // replace old largest largest = data[i]; } } return largest; }

// Problem 04 public static double sumDiffSquare(double[] data1, double[] data2) { double sum = 0.0, diff; for (int i = 0; i < data1.length ; i++) { diff = data1[i] - data2[i]; sum += diff * diff; } return sum; }

// Problem 05 public static double dotProduct(double[] a, double[] b) { double sum = 0.0; for (int i = 0; i < a.length ; i++) { sum += a[i] * b[i]; } return sum; }

// Problem 06 public static double magnitude(double[] vector) { return Math.sqrt(dotProduct(vector,vector)); }

// Problem 07 public static double angleBetween(double[] a, double[] b) { // Law of cosines says A . B = |A||B|cos(Theta) double aDotB = dotProduct(a,b), magA = magnitude(a), magB = magnitude(b), theta = Math.acos(aDotB/(magA*magB)); return theta; }

public static void printArray(double[] arr) { HMCSupport.out.println(); for (int i = 0 ; i < arr.length ; i++) { HMCSupport.out.print(arr[i] + " "); } HMCSupport.out.println(); } }

Last modified August 28 for Fall 99 cs5 by fleck@cs.hmc.edu


This page copyright ©1998 by Joshua S. Hodas. It was built with Frontier on a Macintosh . Last rebuilt on Sat, Oct 31, 1998 at 5:46:58 PM.
http://www.cs.hmc.edu/~hodas/courses/cs5/week_09/labsolutions.html