Exam 2 review Solution
Version 0

 

This lab consists of extra problems relating to methods and arrays to be done in preparation for the exam at the end of week 10.

Note: You will almost certainly not be able to complete all the problems during lab time. You should keep working on them on your own, and seek help from the tutors or professors if you need it. Any one of these would be a reasonable exam question.

The first five problems ask you to write methods which do simple numerical manipulations. It is easiest to build a single class containing all of these methods (added and tested one-by-one) and single main method which gets input from the user to be used in testing the other methods.

The remaining problems require writing methods which manipulate arrays. Again, it is easiest to combine them into a single program. The test arrays may either be input by the user or be given their contents in an initialization step. You might want to use the test program from last week's lab as a shell for this program.

For each of the array problems, make sure that all the methods will work no matter how many elements are in the array you pass to them.

For each of the problems we will show just the method that solves the problem. After problem 5 and 11 give programs that tests all the individual methods.


Problem 01

  Write a method which takes an int as parameter and returns a boolean value indicating whether the number is even.

The first solution is straightforward:

    // Problem 01 version 1
 
    public static boolean even(int n) {
 
        boolean even = false;
 
        if (n%2 == 0) {
 
            even = true;
        }
        return even;
 
    }

But it is much longer than necessary. All that is really necessary is to return the truth value of whether the number is divisible by 2:

    // Problem 01 version b
 
    public static boolean even2(int n) {
 
        return (n%2 == 0);
 
    }


Problem 02

  Write a method which takes two ints as parameters and returns a boolean value indicating whether the first number is a factor of the second number.

    // Problem 02
 
    public static boolean factor(int a, int b) {
 
        return (b%a == 0);
 
    }


Problem 03

  Write a method which takes an int and returns a boolean value indicating whether the given number is prime or not. This method should call the previous one to do some of its work.

    // Problem 03
 
    public static boolean prime(int n) {
 
        boolean prime = true;
 
        if (even(n) && n != 2) {
 
            prime = false;
        }
        else {
 
            for (int i = 3; i <= Math.sqrt(n) ; i++) {
 
                if (factor(i,n)) {
 
                    prime = false;
                }
            }
        }
        return prime;
    }


Problem 04

  Write a method which takes an int and returns as an int the next larger prime number, or the number itself if it is prime. This method should call the previous one to do some of its work.

    // Problem 04
 
    public static int nextPrime(int n) {
 
        while ( !prime(n) ) {   // while n is not prime
 
            n++;        // Note, since n is a COPY of the
        }               // actual values sent in, this does
        return n;       // not screw up that value of n.
    }


Problem 05

  Write a method which takes two ints as parameters and returns a boolean indicating whether they are relatively prime. This method should call the Euclid's Method method written in the lab for week 07 to do the bulk of its work (two numbers are relatively prime if their greatest common factor is ...). If you have not already written that method, write it first.

    // Problem 05
 

public static int euclid(int a, int b) { // Variant of Euclid's method for GCD: repeatedly replace the // larger of the two values with their difference // until they are the same. Will go to 1, if no GCD. while ( a != b ) { if ( a > b) { // replace the larger number with // the difference of the two numbers a = a - b; // Note, since a and b are COPIES } // of the actual values sent in, else { // doesn't mess up the values in the // method which called this one. b = b - a; } } return a; }

public static boolean relativelyPrime(int a, int b) { // a and b are relatively prime if their gcd is 1. return (euclid(a,b) == 1); }


Unified Solution To Problems 1-5:

 

Click Here To Run This Program On Its Own Page
// Program: Review Lab Part 1
// Author:  Joshua S. Hodas
// Date:    November 5, 1998
// Purpose: To solve the first 5 problems in lab 10 using methods
 
import HMC.HMCSupport;
 
class LAB10a {
 
    public static void main(String args[]) {
 
        int x, y;
 
        HMCSupport.out.print("Please enter two integers " +
                             "which will be used to test " +
                             "several methods: ");
        x = HMCSupport.in.nextInt();
        y = HMCSupport.in.nextInt();
 
        if (even(x)) {
 
            HMCSupport.out.println("The value " + x +
                                   " is even.");
        }
        else {
 
            HMCSupport.out.println("The value " + x +
                                   " is not even.");
        }
  
  
        if (factor(x,y)) {
 
            HMCSupport.out.println("The value " + x +
                                   " is a factor of " + y);
        }
        else {
 
            HMCSupport.out.println("The value " + x +
                                   " is not a factor of " + y);
        }
  
  
        if (prime(x)) {
 
            HMCSupport.out.println("The value " + x + " is prime.");
        }
        else {
 
            HMCSupport.out.println("The value " + x + " is not prime.");
        }
  
  
        HMCSupport.out.println("The next prime >= to  " + x +
                               " is " + nextPrime(x));
  
  
        if (relativelyPrime(x,y)) {
 
            HMCSupport.out.println("The values " + x +
                                   " and " + y +
                                   " are relatively prime.");
        }
        else {
 
            HMCSupport.out.println("The values " + x +
                                   " and " + y +
                                   " are not relatively prime.");
        }
   }
  
  
  
    // Problem 01 version a
 
    public static boolean even(int n) {
 
        boolean even = false;
 
        if (n%2 == 0) {
 
            even = true;
        }
        return even;
 
    }
  
  
    // Problem 01 version b
 
    public static boolean even2(int n) {
 
        return (n%2 == 0);
 
    }
  
  
  
    // Problem 02
 
    public static boolean factor(int a, int b) {
 
        return (b%a == 0);
 
    }
  
  
  
    // Problem 03
 
    public static boolean prime(int n) {
 
        boolean prime = true;
 
        if (even(n) && n != 2) {
 
            prime = false;
        }
        else {
 
            for (int i = 3; i <= Math.sqrt(n) ; i++) {
 
                if (factor(i,n)) {
 
                    prime = false;
                }
            }
        }
        return prime;
    }
  
  
  
    // Problem 04
 
    public static int nextPrime(int n) {
 
        while ( !prime(n) ) {   // while n is not prime
 
            n++;        // Note, since n is a COPY of the
        }               // actual values sent in, this does
        return n;       // not screw up that value of n.
    }
 
  
  
    // Problem 05
 

public static int euclid(int a, int b) { // Variant of Euclid's method for GCD: repeatedly replace the // larger of the two values with their difference // until they are the same. Will go to 1, if no GCD. while ( a != b ) { if ( a > b) { // replace the larger number with // the difference of the two numbers a = a - b; // Note, since a and b are COPIES } // of the actual values sent in, else { // doesn't mess up the values in the // method which called this one. b = b - a; } } return a; } public static boolean relativelyPrime(int a, int b) { // a and b are relatively prime if their gcd is 1. return (euclid(a,b) == 1); } }


Problem 06

  Write a method which takes an array of doubles and returns the last element of the array.

    // Problem 06
 
    public static double lastElement(double[] data) {
 
        return data[data.length - 1];
    }


Problem 07

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

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


Problem 08

  Write a method which takes an array of doubles and returns a boolean value indicating whether all the elements in the array are positive.

This first way is better style in that it has only one return statement. On the other hand, it traverses the entire array regardless.

    // Problem 08 version 1
 
    public static boolean allPositive(double[] data) {
 
        boolean allPositive = true;
 
        for (int i = 0; i < data.length ; i++) {
 
            if (data[i] <= 0) {
 
                allPositive = false;
            }
        }
        return allPositive;
    }

The next solution breaks out of the loop early if it finds a 0 or negative value.

    // Problem 08 version b
 
    public static boolean allPositive2(double[] data) {
 
        for (int i = 0; i < data.length ; i++) {
 
            if (data[i] <= 0) {
 
                return false;
            }
        }
        return true;
    }

The best solution, though is a while loop which ends early, but allows for a single return statement:

    // Problem 08 version c
 
    public static boolean allPositive3(double[] data) {
 
        boolean allPositive = true;
        int i = 0;
 
        while (i < data.length && allPositive) {
 
            if (data[i] <= 0) {
 
                allPositive = false;
            }
            i++;
        }
        return allPositive;
    }


Problem 09

  Write a method which takes a double and an array of doubles and returns a boolean value indicating whether the given number occurs as one of the elements of the array.

    // Problem 09
 
    public static boolean inArray(double value, double[] data) {
 
        boolean found = false;
        int i = 0;
 
        while (i < data.length && (!found)) {
 
            if (data[i] == value) {
 
                found = true;
            }
            i++;
        }
        return found;
    }


Problem 10

  Write a method which takes two arrays of doubles and returns a boolean indicating whether the average of the elements in the first is greater than the average of the elements in the second. This should call the method written earlier to compute the averages.

    // Problem 10
 
    public static boolean biggerAverage(double[] data1, double[] data2) {
 
        return  (average(data1) > average(data2));
    }


Problem 11

  Write a method which takes an array of doubles and returns a boolean value indicating whether more than half the elements of the array are greater than the average of the elements of the array.

    // Problem 11
 
    public static boolean halfBiggerThanAverage(double[] data) {
 
        double average = average(data); // Store so don't recompute each time
        int numBiggerThanAverage = 0;
 
        for (int i = 0; i < data.length ; i++) {
 
            if (data[i] > average) {
 
                numBiggerThanAverage++;
            }
        }
        return (numBiggerThanAverage > (data.length / 2));
    }


Unified Solution To Problems 6-11:

 

Click Here To Run This Program On Its Own Page
// Program: ArrayTest2
// Author:  Joshua S. Hodas
// Date:    November 5, 1998
// Purpose: Test solutions to last 6 problems of Lab 10
 

import HMC.HMCSupport; class LAB10b { 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 last element of that array is: "); HMCSupport.out.println(lastElement(a)); HMCSupport.out.print("The average of the elements is: "); HMCSupport.out.println(average(a)); if (allPositive(a)) { HMCSupport.out.println("The array is all positive."); } else { HMCSupport.out.println("The array is not all positive."); } HMCSupport.out.print("Enter a value to search for: "); double searchVal = HMCSupport.in.nextDouble(); if (inArray(searchVal,a)) { HMCSupport.out.println("The value is in the array."); } else { HMCSupport.out.println("The value is not in the array."); } HMCSupport.out.println("The second array being tested:"); printArray(b); HMCSupport.out.print("The average of the elements is: "); HMCSupport.out.println(average(b)); if (biggerAverage(a,b)) { HMCSupport.out.println("The average of the first is bigger."); } else { HMCSupport.out.println("The average of the second is bigger."); } if (halfBiggerThanAverage(b)) { HMCSupport.out.println("More than half the second is bigger" + " than average."); } else { HMCSupport.out.println("Less than or equal to half the second" + "is bigger than average."); } } // Problem 06 public static double lastElement(double[] data) { return data[data.length - 1]; } // Problem 07 public static double average(double[] data) { double sum = 0; for (int i = 0; i < data.length ; i++) { sum += data[i]; } return sum / data.length; } // Problem 08 version a public static boolean allPositive(double[] data) { boolean allPositive = true; for (int i = 0; i < data.length ; i++) { if (data[i] <= 0) { allPositive = false; } } return allPositive; } // Problem 08 version b public static boolean allPositive2(double[] data) { for (int i = 0; i < data.length ; i++) { if (data[i] <= 0) { return false; } } return true; } // Problem 08 version c public static boolean allPositive3(double[] data) { boolean allPositive = true; int i = 0; while (i < data.length && allPositive) { if (data[i] <= 0) { allPositive = false; } i++; } return allPositive; } // Problem 09 public static boolean inArray(double value, double[] data) { boolean found = false; int i = 0; while (i < data.length && (!found)) { if (data[i] == value) { found = true; } i++; } return found; } // Problem 10 public static boolean biggerAverage(double[] data1, double[] data2) { return (average(data1) > average(data2)); } // Problem 11 public static boolean halfBiggerThanAverage(double[] data) { double average = average(data); // Store so don't recompute each time int numBiggerThanAverage = 0; for (int i = 0; i < data.length ; i++) { if (data[i] > average) { numBiggerThanAverage++; } } return (numBiggerThanAverage > (data.length / 2)); } 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(); }

}


This page copyright ©1998 by Joshua S. Hodas. It was built with Frontier on a Macintosh . Last rebuilt on Thu, Nov 5, 1998 at 9:26:05 PM.
http://www.cs.hmc.edu/~hodas/courses/cs5/week_10/labsolutions.html