CPSC 124, Spring 2021: Sample Answers to Quiz #3

These are sample answers only.

Question 1. Show the exact output from the following code segment:

    int a, b;
    a = 4;
    b = 1;
    while ( b <= 5 ) {
        b = b + 1;
        if ( b > 3 ) {
            a = a / 3;
        } else {
            a = a * 2;
        }
    }
    System.out.println(a + "," + b);

Answer. The answer to the problem as written is: 0,6. There is only one line of output, because the System.out.println statement comes after the while loop. I meant the output statement to be inside the while loop, and in that case, the answer would be:

      8,2
      16,3
      5,4
      1,5
      0,6

To see why, you have to execute the code step by step as the computer would do it, keeping track of the values of a and b. Here is how the values change as the loop runs:

      a:  4  8  16  5  1  0
      b:  1  2   3  4  5  6

Note that when doing integer division, 16/5 gives 3, 5/3 gives 1, and 1/3 gives 0. The last time through the loop, b becomes six and the test in the loop becomes false, so the loop ends.

Question 2. Briefly explain the meaning of each of the following Java operators:

          a)   %
          b)   &&
          c)   ++

Answer.

a) % is the remainder operator. If x and y are numbers, then x%y is the remainder when x is divided by y.

b) && is the boolean operator that means "and". It is used to combine boolean values, such as  (x >= 3) && (x < 10)

c) ++ is an operator that acts on a numeric variable by adding one to its value. The statement x++; has the same effect as x=x+1; (Note that x++ is also an expression, and its value is the old value of x, not the new value.)

Question 3. Fill in the following program so that it does the following: Simulate flipping a coin seven (7) times. When the coin shows heads, print out "Heads"; when the coin shows tails, print out "Tails". A sample output from the program is shown at the right.

public class Flips {                                          Heads
    public static void main(String[] args) {                  Tails
        .                                                     Tails
        .                                                     Tails
        .                                                     Heads
    }                                                         Tails
}

Answer.

public class Flips {
    public static void main(String[] args) {
    
        int flips; // Number of times coin has been flipped.
        flips = 0;
        while (flips < 7) {
            if ( Math.random() < 0.5 ) {
                System.out.println("Heads");
            }
            else {
                System.out.println("Tails");
            }
            flips = flips + 1;
        }
    
    }
}