CPSC 124, Spring 2017: Sample Answers to Quiz #2

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. Write a complete program that inputs one integer from the user, then tells the user "That number is odd" or "That number is even", depending on whether the number is odd or even. (Recall that the % operator can be used to test for odd/even.)

Answer.

      public class EvenOrOdd {
          public static void main(String[] args) {
              int input;  // the user's number
              System.out.print("Enter an integer: ");
              input = TextIO.getlnInt();
              if (input % 2 == 0) {
                  System.out.println("That number is even.");
              }
              else {
                  System.out.println("That number is odd.");
              }
          }
      }

Question 2. Write a while loop that prints out the integers from 100 down to 1, one to a line. (Note that the numbers are printed in reverse order.)

Answer.

      int count = 100;
      while ( count > 0 ) {
          System.out.println(count);
          count = count - 1;
      }

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

        int x = 2;
        int y = 60;
        while ( y > 0 ) {
             y = y / x;
             x = x + 1;
             System.out.println( x + ", " + y);
        }
        System.out.println("Done");

Answer. The variables x and y are assigned initial values 2 and 60. The first time through the loop, the assignment statement y = y / x; divides 60 by 2 and assigns the answer, 30, to y. The next statement adds 1 to x, giving 3. So the first output is: 3, 30. The second time through the loop, y is divided by 3, giving 10, and x increases to 4. The second output is: 4, 10. In the third iteration of the loop, 10 is divided by 4 to get the new value of y. Since the variables are int, the division discards the remainder, so the new value of y is 2. The fourth output is: 5, 2. In the fourth iteration, 2 is divided by 5, which gives the answer zero for int variables. The fourth output is: 6, 0. Then, since y is zero, the loop ends. Here is the output:

       3, 30
       4, 10
       5, 2
       6, 0
       Done