CPSC 124, Spring 2006
Answers to Quiz #3


Question 1: Define the term algorithm.

Answer: An algorithm is an unambiguous step-by-step procedure for performing some task, which is guaranteed to terminate after a finite number of steps.


Question 2: What is meant by pseudocode?

Answer: Pseudocode refers to informal language used to describe algorithms, as opposed to following the very strict syntax rules of an actual programming language. Pseudocode is used during the development stage of an algorithm, as a way to help think about the design of the algorithm.


Question 3: What is debugging?

Answer: Debugging refers to finding and fixing the semantic errors in a program that show up when the program is run but does not behave as expected.


Question 4: Write an if statement that will simulate flipping a coin. Print out either "Heads" or "Tails." There should be a 50% chance that the output is "Heads" and a 50% chance that the output is Tails.

Answer: Here are two possible answers:

       if ( Math.random() < 0.5 )                    int choice;
           System.out.println("Heads");              choice = (int)( 2 * Math.random() );
       else                                          if (choice == 0) {
           System.out.println("Tails");                 System.out.println("Heads");
                                                     }
                                                     else {
                                                        System.out.println("Tails");
                                                     }

Question 5: Write a while loop that will read a positive integer from the user. (Use the loop to make absolutely sure that the number is greater than zero.)

Answer:

          int usersNum;
          System.out.print("Please enter a positive integer:  ");
          usersNum = TextIO.getlnInt();
          while ( usersNum <= 0 ) {
              System.out.println("Answer must be greater than zero."):
              System.out.println("Please enter a positive integer:  ");
              usersNum = TextIO.getlnInt();
          }

Question 6: Circle the syntax errors in the following Java code, and state briefly what is wrong in each case:

          int ct;
          ct = 0;
          while ct < 10 {
             ct++;
             if (ct % 2 = 0)
                System.out.println(ct);
          }

Answer: There are two errors. The first error is in the third line: The condition in a while loop must be enclosed in parentheses, so it should read:

          while ( ct < 10 ) {

The second error is in the fifth line. The operator for testing equality is "==", not "=", so that it should read:

          if ( ct % 2 == 0 )

David Eck, 10 February 2006