CS 124, Fall 2009
Solutions to Quiz #2

1. Describe the effect of the following statement in Java, where number is a variable of type int:

number++;

Answer: When this statement is executed, the value that is stored in the variable number is increased by 1. For exmple, if the value is 16 before the statement is executed, then the value 17 will be stored in number after the statment is executed. (Note: This assumes that number has been declared to be of some numeric type, such as int or double.)

2. What is an algorithm?

Answer: An algorithm is a definite step-by-step procedure for performing some task, which is guaranteed to finish after a finte number of steps.

3. Show the exact output produced by the following code segment:

   int n;
   n = 22;
   while (n > 0) {
      System.out.println( n % 2 );
      n = n / 2;
   }

Answer: (The first time through the loop, the value of n is 22, and n % 2 is 0, since 2 goes evenly into 22 with no remainder. So the output from the first execution of the loop is a 0 on a line by itself. The statement n = n / 2 sets n = 11, and the loop is then repeated with this new value of n. Witn n = 11, the value of n % 2 is 1, and the output is a 1 on a line by itself. Overall, n takes on the values 22, 11, 5, 2, 1, and 0. When n becomes 0, the loop ends. The outputs are 22 % 2, 11 % 2, 5 % 2, 2 % 2, and 1 % 2. That is, the outputs are 0, 1, 1, 0, and 1. Note that the loop ends before it has a chance to print 0 % 2.)

So, the exact ouput of the code segment is:

              0
              1
              1
              0
              1

4. Write an if statement to complete the following program. If the user's input (answer) is 13, then the program should output the message "Correct"; otherwise, the program should output the message "Wrong".

public class Greet {
   public static void main(String[] args) {
      int answer;
      System.out.print("What is 5 + 8 ? ");
      answer = TextIO.getlnInt();


   }
}

Answer:

public class Greet {
   public static void main(String[] args) {
      int answer;
      System.out.print("What is 5 + 8 ? ");
      answer = TextIO.getlnInt();
      if ( answer == 13 ) {
         System.out.println("Correct");
      }
      else {
         System.out.println("Wrong");
      }
   }
}