CPSC 124, Fall 2001
Frist Test, October 1

This is the first test in CPSC 124: Introductory Programming.


Question 1: Define each of the following terms, as they apply to this course:

a) algorithm
b) machine language
c) compiler

Answer:

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

b) Machine language refers to a programming language that is executed directly by the hardware of a computer. Machine language instructions are coded as binary numbers. Every type of computer has its own machine language.

c) A compiler is a computer program that translates programs written in some high-level computer language into machine language programs. Unlike an interpreter, a compiler does a translation all at once, producing a complete machine language program.


Question 2: When you are debugging a program, are you trying to fix sytactic errors, or are you trying to fix semantic errors? Explain your answer.

Answer: Bugs are errors that cause a program to give incorrect results or to display incorrect behavior. A program with bugs is syntactically correct, or else it couldn't even be compiled. So a bug is a semantic error. The code doesn't actually mean what you were trying to express. Debugging refers to finding semantic errors.


Question 3: What is meant by the type of a variable? Give some examples of types that are used in Java.

Answer: A variable in Java can only store data of one specified type. The "type" of a variable simply refers to the type of data that it can hold. Some of the types that can be used in Java are: int, double, boolean, char, and String. A variable of type int can only hold whole numbers, a variable of type double can hold numbers that can contain a decimal point, and so on.


Question 4: The function Math.random() returns a random number between 0.0 and 1.0, so it has a 50% chance of being less than 0.5. Write a program segment that uses this fact to simulate flipping a coin. Your segment should select a random number. It should print "Heads" if the random number is less than 0.5, and it should print "Tails otherwise.

Answer:

          if ( Math.random() < 0.5 ) {
             System.out.prinln("Heads");
          }
          else {
             System.out.println("Tails");
          }

The braces, { and }, in this answer are optional because in each case the braces contain just one statement.


Question 5: Suppose that you want to write a "password-protected program." To run the program, a user must know that the password is fred. Write a loop that you could use at the beginning of the program to force the user to enter the password. The loop should ask the user for a password and compare the users response to the String "fred". The loop should continue asking the user for the password until the user responds correctly with fred as the password.

Answer: There are many ways to write this loop. Here are a few:

     Version 1:   String pw;
                  do {
                     System.out.print("Enter the password: ");
                     pw = TextIO.getln();
                  } while ( ! pw.equals("fred") );
                  

     Version 2:   String pw;
                  while (true) {
                     System.out.print("Enter the password: ");
                     pw = TextIO.getln();
                     if (pw.equals("fred"))
                        break;
                     System.out.println("Incorrect password.  Try again.");
                  }
                  

     Version 3:   String pw;
                  pw = "bad";  // bad password, to prime the loop
                  while ( ! pw.equals("fred") ) {
                     System.out.print("Enter the password: ");
                     pw = TextIO.getln();
                  }
                  

     Version 4:   // This one's a bit crazy
                  String pw;
                  for (pw = "bad"; !pw.equals("Fred"); pw = TextIO.getln()) {
                     System.out.print("Enter the password: ");
                  }

Question 6: Show the exact output produced by the following Java code segment:

           int f,n,k;
           f = 1;
           n = 1;
           while (f < 5) {
              k = f;
              f = n + f;
              n = k;
              System.out.println("f = " + f);
              System.out.println("n = " + n);
           }

Answer: The output is shown on the right below. On the left is a table that shows the values of the variables as they change during the execution of the loop.

                            |  k  f  n         
     -----------------------|----------         ANSWER:
     Before the loop        |  -  1  1          OUTPUT IS
     -----------------------|----------         -----------
     1st time through loop  |  1  2  1             f = 2
     -----------------------|----------            n = 1
     2nd time through loop  |  2  3  2             f = 3
     -----------------------|----------            n = 2
     3rd time through loop  |  3  5  3             f = 5
     -----------------------|----------            n = 3
     Loop ends since f >= 5 |

Note: If this loop is continued indefinitely, instead of stopping after f becomes greater than or equal to 5, the values of f form a famous mathematical sequence called the Fibonacci sequence.


Question 7: Consider the following Java program:

           public class Guess {
              public static void main (String[] args) {
                 int x,p;
                 int n,i;
                 System.out.print("Type an integer: ");
                 x = TextIO.getlnInt();
                 System.out.print("Type a positive integer: ")
                 n = TextIO.getlnInt();
                 p = 1;
                 for (i = 0; i < n; i++) {
                    p = p * x;
                 }
                 System.out.println("Answer: " + p); 
             }
           }

a) What will the program output if the user enters the numbers 2 and 1 when the program is run?
b) What will the program output if the user enters the numbers 2 and 3 when the program is run?
c) What, in general, is the purpose of this program? That is, what is the meaning of the answer computed by the program when the user enters some integer x and some positive integer n ?

Answer:

a) On an input of 2 and 1, the output is "Answer: 2". b) On an input of 2 and 3, the output is "Answer: 8". c) More generally, the program computes the value of x raised to the power n. Given inputs for x and n, the program starts with p=1 and multiplies this by x a total of n times. The result is 1*x*x*x*...*x where x occurs n times. This product is x raised to the n-th power.


Question 8: For this problem, you should write a complete Java program, as it would appear in a Java source code file. Your program will print out and count the divisors of a given integer. An integer D is said to be a divisor of an integer N if N D == 0.

Your program should do the following: Get an integer, N, from the user. Find and print all the integers D in the range from 1 to N, inclusive, for which D is a divisor of N. At the end of the program, you should print out the number of divisors of N that you have found.

Answer: Here is a program with comments. The comments are not a required part of the answer.

      public class CountDivisors {
      
         public static void main(String[] args) {
         
            int N;     // Numbers whose divisors we are counting.
            int D;     // A number to be tested to see if it divides N.
            int count; // The number of divisors of N that we have found. 
            
            // Get the number N from the user.

            System.out.print("Enter a value for N: ");
            N = TextIO.getlnInt();
            
            // Initialize the counter to zero before we start counting.
            
            count = 0;
            
            // Use a for loop to test each number between 1 and N,
            // inclusive, and print and count the cases in which the 
            // number is a divisor of N.
            
            System.out.println("The divisors of " + N + " are:");
            for ( D = 1; D <= N; D++ ) {
               if ( N % D == 0 ) {
                    // D is a divisor of N, so count it and print it.
                  count = count + 1;
                  System.out.println(D);
               }
            }
            
            // Print out the number of divisors we have counted.
            
            System.out.println("The number of divisors was " + count);
            
         } // end main()
         
      } // end class CountDivisors

Question 9: What is meant by good programming style? Why is it important to follow the rules of good programming style? Discuss at least two different rules of good style and explain the purpose of each rule.

Answer: Good programming style refers to writing your programs in a way that will make it easier for human readers (including yourself) to read and understand the program. Style includes the names you choose for variables, the way you lay out the program on the page, and the comments that you add to the program. None of these style elements make the least bit of difference to the computer, but they are essential for people who are trying to read the programs.

One style rule is to use meaningful variable names. This is important because it makes it easier to understand the meaning of assignment statements and other computations that use the variable. For example, it is much easier to understand the purpose of the statement "interest = principal * interestRate;" than it is to understand "x=p*r;". The latter statement gives no clue to the reader about what is going on!

Another important style rule is to use indentation to show the structure of the program. That is, statements that are nested inside another statement should be evenly indented a few spaces more than the enclosing statement is indented. Without such indentation, it is very hard for the reader to tell where a block of statements begins and where it ends.


David Eck, eck@hws.edu