Midterm Preparation

The midterm exam is coming up on Wednesday, October 14. This exam will cover chapters 1 through 6. I will post the exam problems to the course web site at 9 AM on the 14th. You will have until 9 AM on the 15th to complete your work and send your work to me.

The exam is open book and open note. You are welcome to use any of the lecture notes and example projects on the course web site during the exam.

To help you prepare for the exam, here is a list of suggested problems from the text for you to try. These are all even numbered problems, so you can access the solutions to these problems from the textbook's companion site.

Chapter 3: 8, 18, 22

Chapter 4: 14, 24

Chapter 5: 10, 12, 16, 18

Chapter 6: 6, 14, 18

Sample Questions

Here some sample exam problems from previous years.

First sample problem

Some positive integers can be written as the sum of the squares of two nonzero integers and some can not. For example, 13 = 22 + 32, while 15 can not be written as the sum of two squares. Write a program that prompts the user to enter an integer and then determines whether or not that integer can be written as the sum of two squares.

Solution

public class CheckNumber {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int solutionCount = 0;

    System.out.print("Enter an integer: ");
    int n = input.nextInt();

    for(int a = 1; a < n; a++) {
      for(int b = 1; b < n; b++) {
        if (a * a + b * b == n) {
          System.out.println(n+" = "+a+"^2+"+b+"^2");
          solutionCount++;
        }
      }
    }

    if(solutionCount == 0)
       System.out.println(n+" is not the sum of two squares.");
  }
}

Second sample problem

Write the code for a method

public boolean distinct(int a,int b,int c)

which returns true if the integers a, b, and c are all different and false if they are not.

Use this method in a main method that generates random integers in the range from 1 to 10 three at a time until it generates a set of three integers that are distinct. Your program should then print the first set of distinct integers it generates. To generate a random integer in the range from 1 to 10 you can use the code

Random rnd = new Random();
int n = rnd.nextInt(10) + 1;

Solution

public class ThreeIntegers {
  public boolean distinct(int a,int b,int c) {
    if(a == b || a == c || b == c)
      return false;
    return true;
  }

  public static void main(String[] args) {
    Random rnd = new Random();
    int one = 0;
    int two = 0;
    int three = 0;
    while(distinct(one,two,three) == false) {
      one = rnd.nextInt(10) + 1;
      two = rnd.nextInt(10) + 1;
      three = rnd.nextInt(10) + 1;
    }
    System.out.println(one + "," + two + "," + three);
  }
}