Review for Midterm 0

One-page version suitable for printing.

Question 0-1

Write a program to print a triangle of asterisks as in the third problem of Lab 0.

Width? 5
*****
****
***
**
*
To accomplish this, define two static methods. The first takes a parameter num and prints a line containing num asterisks. And the main() method should use this method to accomplish the overall task.
import csbsju.cs160.*;

public class PrintTriangle {
    public static void printlnStars(int num) {



    }
    public static void main(String[] args) {



    }
}

Question 0-2

Consider the following method to compute the greatest common denominator of two numbers.

public static int gcd(int m, int n) {
    int r;
    while(n != 0) {
        r = m % n;
        m = n;
        n = r;
    }
    return m;
}
Say we call gcd(32,20). Show how the values of r, m, and n change as the computer continues through the method.
r
m 32
n 20

Question 0-3

The following program uses the Account class we defined in class.

import csbsju.cs160.*;

public class PrintHello {
    public static void main(String[] args) {
        Account a = new Account();
        Account b = new Account();
        a.deposit(81.0);
        b.withdraw(3.0);
        a = b;
        a.deposit(9.0);
        b = new Account();
        b.withdraw(1.0);
        IO.println(a.getBalance());
    }
}
What does this program print?

Solution

Question 0-4

Consider the following class method.

public static void mystery(int[] arr) {
    for(int i = arr.length - 1; i > 0; i--) {
        arr[i] = 10 + arr[i - 1];
    }
    for(int i = 0; i < arr.length; i++) {
        IO.print(arr[i]);
    }
}
Suppose we were to pass the array { 1, 4, 5 } into this method. What would the method print?

Solution

Question 0-5

Define a new class Rect that can be used to create an object representing a rectangle. The constructor method for Rect should take two parameters, both doubles: the rectangle's width and the rectangle's height. The class should support the following object methods.

double getPerimeter() Returns the length of the rectangle's perimeter.
double getArea() Returns the area of the rectangle.
boolean canContain(Rect other) Returns true if other can fit within the rectangle. (in its current configuration or rotated 90 degrees).
public class Rect {
    // your answer here...


}

Solution