Midterm Review Questions Solutions

  1. Write a function called isPositive(x) that returns true if x is greater than 0, and false if x is 0 or less. For example:

    isPositive(0) returns false

    isPositive(4.0) returns true

    isPositive(-5.3) returns false

    Sample solution:

    boolean isPositive(float x) {
            if (x > 0) {
                    return true;
            } else {
                    return false;
            }
    }
    
    // or ...
    boolean isPositive(float x) {
            return x > 0;
    }
    
  2. Write a function called sign(x) that returns the sign of x, i.e. -1 of x is less than 0, 0 if x is equal to 0, and 1 if x is greater than 0. For example:

    sign(-4) returns -1

    sign(-5.3) returns -1

    sign(0) returns 0

    sign(4) returns 1

    sign(53.2) returns 1

    Sample Solution:

    int sign(float x) {
            if (x < 0) {
                    return -1;
            } else if (x > 0) {
                    return 1;
            } else {
                    return 0;
            }
    }
    
  3. Write a function called min(x, y) that returns the smaller of x and y. For example:

    min(1, 2) returns 1

    min(2, 1) returns 1

    min(-85, 2) returns 2

    min(3, 3) returns 3

    Sample solution:

    int min(int x, int y) {
            if (x < y) {
                    return x;
            } else {
                    return y;
            }
    }
    
  4. Write a function called dist(x, y) that returns the positive difference between x and y.

    dist(1, 2) returns 1

    dist(2, 1) returns 1

    dist(-5, 2) returns 7

    dist(3, 3) returns 0

    Sample solution:

    int dist(int x, int y) {
            float d = x – y;
            if (d < 0) {
                    return -d;
            } else {
                    return d;
            }
    }
    
    // or ...
    int dist(int x, int y) {
            return abs(x - y);
    }