CPSC 124, Fall 2011
Quiz #2

Question 1. Define the term algorithm.

Answer. An algorithm is an unambiguous (or definite) step-by-step procedure for carrying out some task, which is guaranteed to end after a finite number of steps.

Question 2. What is meant by a type-cast? Give an example to show what a type-cast looks like in a Java program.

Answer. A type-cast is an operation that converts a value of one type into another type. For example, a value num of type double can be converted to type int with the expression

(int)num

In this case, the real number is "truncated" to an integer by discarding the fractional part. (Type-casts are necessary in cases when Java does not perform automatic type conversion, usually when doing the conversion loses some information, as in the example above where the fractional part of a real number is lost.)

Another example would be casting one of the operands in an integer division to double, in order to get the real-number quotient. For example,

average  =  ((double)total) / count;

Question 3. Explain what the following code segment does.

int d1, d2, total;
d1 = (int)(6*Math.random() + 1);
d2 = (int)(6*Math.random() + 1);
total = d1 + d2;
if ( total == 7 || total == 11 ) {
     System.out.println("You won.");
}
else {
     System.out.println("You lost.");
}

Answer. This code segment simulates rolling two dice (by randomly selecting two integers in the range 1 to 6). If the total roll is 7 or 11, then it says "You won." If not, it says, "You lost." It seems to be simulating a simple dice game. [Actually, its the first part of a simulation of a game of craps.]

Question 4. Complete the following program so that it does the following: Use a while loop to write out all the integers from 1 to 100 (inclusive).

public class Greet {
    public static void main(String[] args) {


    }
}

Answer.

public class Greet {
    public static void main(String[] args) {

        int n;  // the number to be output
        n = 1;  // start with 1
        while (n <= 100) {
           System.out.println(n);
           n++;  // [ Reminder:  n++;  means  n = n + 1; ]
        }

    }
}

This could also be done as:

public class Greet {
    public static void main(String[] args) {

        int n;  // the number to be output
        n = 0;  // start with 0 (which will NOT be printed)
        while (n < 100) {
           n++;
           System.out.println(n);
        }

    }
}