CPSC 124, Spring 2013
Sample Answers to Quiz #3

Question 1. Define the term algorithm.

Answer. An algorithm is an unambiguous, step-by-step procedure for performing some task (or solving some problem) that is guaranteed to finish after a finite number of steps.

Question 2. Show the exact output, including line breaks and spaces, produced by the following Java code:

      int a, b;
      a = 20;
      b = 1;
      while ( a > b ) {
         a = a - 5;
         b = b * 2;
         System.out.println( a + "  " + b );
      }

Answer.

         15 2
         10 4
         5 8

(To find the answer, you have to follow the code line-by-line and do what each line says, just as the computer does. Note that the while loop repeats as long as a is greater than b. And note that the formula in the output statement -- a + " " + b -- creates a String consisting of the value of a followed by a space followed by the value of b.)

Question 3. Complete the following program so that it does the following: The program should get an integer from the user. Then it should output the string "Hello World!" in a loop, where the number of times that the string is output is equal to the number typed in by the user. For example, if the user entered 867, then the program should output "Hello World!" 867 times. Use a while loop. You can assume that the user's number is positive; you do not need to test it.

Answer.

public class ManyGreetings {

  public static void main(String[] args) {
      
      int numberOfGreetings;  // The number of times to say Hello World.

      int count;  // For counting the number of times we have said it.
      
      System.out.print("How many greetings? ");
      numberOfGreetings = TextIO.getlnInt();
      
      count = 0;
      
      while ( count < numberOfGreetings ) {
          System.out.println( "Hello World!" );
          count = count + 1;
      }
      
  }

}