CPSC 124, Fall 2017: Sample Answers to Quiz #3

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

Question 1. Algorithms are a central concern of computer science. Give a careful definition of the term algorithm.

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

Question 2. What is a bug, as the term applies to computer programming?

Answer. A bug is a semantic error in a program that shows up at run time, when the program crashes or gives an incorrect result.

Question 3. he following code segment is meant to make absolutely sure that that user enters an integer that is greater than zero. Why doesn't it do this? What has the changed to make it work correctly?

int n;
System.out.print("Enter a positive number: ");
n = TextIO.getlnInt();
if ( n <= 0 ) {
   System.out.println("Bad input.  Try again.");
   System.out.print("Enter a positive number: ");
   n = TextIO.getlnInt();
}

Answer. The user might input a negative number on the second try as well as on the first try. To be absolutely sure that n is positive in the end, the if statement should be changed to a while statement. (It is only necessary to change the word "if" to "while".)

Question 4. Complete this "while (true)" loop so that it makes a and b equal to two different random integers in the range 1 to 10.

int a,b;
while (true) {

}
// At this point, we are sure that a is not equal to b

Answer.

int a,b;
while (true) {
    a = (int)( 10*Math.random() + 1 );
    b = (int)( 10*Math.random() + 1 );
    if ( a != b ) {
       break;
    }
    // (if a is equal to b, continue looping)
}
// At this point, we are sure that a is not equal to b