CPSC 124, Spring 2006
Answers to Test #1


Question 1: Define each of the following terms, as it relates to this course:

       a) algorithm

       b) compiler

       c) type (of a variable)

Answer:

       a) An algorithm is an unambiguous, step-by-step procedure for solving a certain task that is guaranteed to finish after a finite number of steps.

       b) A compiler is a computer program that translates programs written in a high-level language into equivalent programs expressed in another language, such as machine language.

       c) The "type" of a variable specifies what kind of values that variable can hold. For example, a variable of type int can hold 32-bit integer values and no other type of value. A variable's type is specified when the variable is declared. For example, the declaration "int x;" declares a variable named x of type int.


Question 2: Java has five control statements: if, while, do...while, for, and switch. However, it really only needs two of these. What does this mean? Why is it true?

Answer: The two basic types of control statements are loops and branches. A loop repeats a segment of code over and over, while a branch selects among several possible courses of action. These capabilites are necessary in order to express all possible algorithms.

Among Java control statements, while, do...while, and for are looping statements. Having three different looping statements makes it easier to express certain types of loops. For example, a counting loop can most easily be written as a for loop, while a loop where the continuation test comes most naturally at the end can be most easily written as a do...while. However, although three looping statements are convenient, they are not necessary. Any one of them would suffice. For example, any do...while or for is equivalent to some while loop, so we could eliminate do..while and for without making the language less powerful.

Similarly, if and switch are both branching statements. Although it is convenient to have both, anything that can be expressed with a switch statement could also be expressed with if, so eliminating the switch statement would not reduce the power of the language.


Question 3: Write a code segment that will multiply two integers that are input by the user. Ask the user for each integer and read the response. Compute the product and print out the answer. Use TextIO for input. (Yes, this is easy.)

Answer:

           int x, y;  // the numbers to be read from the user
           int prod;  // the product of x and y
           
           System.out.print("Enter your first number:   ");
           x = TextIO.getlnInt();
           System.out.print("Enter your second number:  ");
           y = TextIO.getlnInt();
           
           prod = x * y;
           
           System.out.println("The product is " + prod);

Question 4: Assume that str is a variable of type String that has already been defined. What is the purpose of the following code segment?

         String r;
         r = "";
         int index;
         for ( index = str.length() - 1; index >= 0; index-- ) {
               r = r + str.charAt(index);
         } 

Answer: This code segment computes the "reverse" of a string. That is, after this code segment has been executed, the string r contains the same characters as the string str, but in reverse order. For example, if the value of is "Hello World", then the value of r will be "dlroW olleH".

(This is true because the for loop looks at the characters of str in reverse order from position str.length()-1 (the last position in the string) down to position 0 (the first position in the string). As each character is accessed, it is added onto the string r, so the last character of str comes first in r, the next-to-last character in str comes second in r, and so on.)


Question 5: Assume that str is a variable of type String that has already been defined, and that the value of str is a string that contains only lower-case letters. Write a code segment that will count the number of vowels in str. Print the answer at the end of the code segment. (Note: A vowel is defined to be one of the characters 'a', 'e', 'i', 'o', or 'u'.)

Answer: (To test whether a character ch is a vowel, you want to test whether ch is 'a' or ch is 'b' or...)

           int vowelCount;  // This will be the number of vowels.
           int index;       // For referencing the character positions in str.
           
           vowelCount = 0;
           
           for ( index = 0; index < str.length(); index++ ) {
              char ch;  // Character in position index; used for convenience.
              ch = str.charAt(index);
              if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                 vowelCount++;
           }
           
           System.out.println("The number of vowels in \"" + str + "\" is " + vowelCount);

Question 6: Explain the meanings of the operators / and % when they are applied to integer values.

Answer: When used with integers, / represents the integer quotient. That is, N / M is the integral number of times that M goes into N, disregarding the remainder. The % operator gives the remainder. For example, 7398 / 100 is 73, while 7398 % 100 is 98.


Question 7: For each of the following code segments, how many times will ``Hello World'' be printed out when the code segment is executed? Briefly explain each answer. Be careful; some of these are tricky!

        a)  int i;
            for (i = 0; i <= 10; i++)
               System.out.println("Hello World");


        b)  int i;
            for (i = 0; i < 10; i--)
               System.out.println("Hello World");


        c)  int i;
            for (i = 1; i < 10; i++) {
               if ( i % 3 == 0 )
                  System.out.println("Hello World");
            }

        d)  int i;
            for (i = 1; i <= 25; i++);
               System.out.println("Hello World");

Answer:

       a) Prints "Hello World" eleven times, since i goes from 0 to 10, including both endpoints, and hence takes on 11 different values.

       b) This is an infinite loop, which outputs "Hello World" over and over indefinitely -- an infinite number of times if it is not interrupted in some way. This is because i starts out at zero and goes down from there, so the continuation condition i < 10 will always be true. (Note: A more accurate answer would take note of the fact that int values in Java are only 32 bits long, so when i reaches the most negative int value, the next i-- will change it to a positive value and the loop will end. This will be after "Hello World" has been printed 2,147,483,649 times.)

       c) The expression "i % 3 == 0" is true when i is evenly divisible by 3. For i between 1 and 10, this will happen when i is 3, 6, or 9. So, "Hello World" will be printed three times.

       d) This prints "Hello World" once. The for loop repeats 25 times, but the only thing inside the for loop is an empty statement, because of the ";" at the end of the line. So, this does nothing 25 times, and only then does it get to the output statement, which is executed only once.


Question 8: Show the exact output produced by the following code segment. This code segment has no particular purpose; you just have to follow it through the way a computer would. (If your answer is incorrect, you might get partial credit by explaining your answer.)

    int a, b, c;
    a = 18;
    b = 1;
    c = 1;
    while ( a > 0 ) {
       b = b + c;
       a = a / b; 
       c++;
       System.out.println(a + "," + b + "," + c);
    }

Answer:

        9,2,2
        2,4,3
        0,7,4

Question 9: Write a complete Java program -- starting with public class... -- that does the following: Simulate rolling a pair of dice 1000000 times, and count the number of times that the total roll is equal to 7. Print out the answer at the end. You do not need to add any comments to your code.

Answer:

         public class Count7 {
         
            public static void main(String[] args) {
            
               int d1, d2;  // Numbers showing on the two dice.
               int roll;    // The total of the two dice.
               int sevens;  // The number of sevens rolled so far.
               
               int ct;      // Counter variable for the for loop.
               
               for (ct = 0; ct < 1000000; ct++) {
                  d1 = (int)(6*Math.random() + 1);
                  d2 = (int)(6*Math.random() + 1);
                  roll = d1 + d2;
                  if (roll == 7)
                     sevens ++;
               }
               
               System.out.println("Among 1000000 rolls, the number of sevens was: " + sevens);
            
            }   
         
         }

David Eck, 17 February 2006