CPSC 124, Fall 1996
First Test
This is the first test given in CPSC 124: Introductory Programming, Fall 1996. See the information page for that course for more information.
The answers given here are sample answers that would receive full credit. However, they are not necessarily the only correct answers.
Question 1: Define Each of the following terms, as they relate to this course:
a) machine language
Answer: Machine language refers to the set of instructions that can be executed directly by the central processing unit of a computer. Each type of computer has its own machine language. Programs written in any other language must be translated into machine language before they can be executed by the computer.
b) local variable
Answer: A local variable is one that is declared inside a subroutine. Such a variable is only accessible from inside the subroutine, and it exists only as long as the subroutine is running. In Java, variables can also be local to a block, which is any set of statements enclosed between { and }.
c) instance variable
Answer: An instance variable is part of an object. An object can contain data, and that data is stored in instance variables. The instance variables of an object are determined by the class of that object, but the actual variables belong to individual objects, not to the class. Each object of the class has its own set of instance variables.
d) contract of a subroutine
Answer: The contract of a subroutine refers to everything that one needs to know about the subroutine in order to use it correctly. The contract includes both syntactic information (the return type, name, and parameter types of the subroutine) and semantic information (a description of what task the subroutine performs, and any restrictions on what parameter values it can handle). However, it does not include the implementation of the subroutine, since that is not something you need to know when you just want to use the subroutine.
Question 2: In a Java application, the main() subroutine must be declared to be both static and public.
a) Why must the main() routine be static? (Why does this requirement make sense?)
Answer: If the main routine were not static, then it would have to be part of some object. However, no object can be created by the program until the program starts running. Running the program means running the main() routine, so the main() routine must exist independently of any object and must therefore be static.
b) Why must the main() routine be public? (Why does this requirement make sense?)
Answer: Making the main() routine public means that it can be accessed from outside the class (and, technically, from outside the "package" in which it is defined). Since the main() routine is called from outside, by the system, it must be public so that the system can access it.
Question 3: Write a complete Java subroutine named pythagorus. It should have two parameters, x and y, of type double. It should compute and return as its value: the square root of (x2 + y2).
Answer:
static double pythagorus(double x, double y) { return Math.sqrt( x*x + y*y ); }
Question 4: Recall that the two statements
die1 = 1 + (int)(Math.random() * 6); die2 = 1 + (int)(Math.random() * 6);can be thought of as rolling a pair of dice. Write a complete Java program that will roll a pair of dice over and over for some specified number of times, and will count the number of times that the sum of the two dice is 7. The number of times that the dice are to be rolled is to be typed in by the user. The number of sevens is to be output by the computer on the console.
Answer:
class CountSevens { public static void main(String[] args) { Console console = new Console(); int die1, die2; // the dice int total; // the total roll, die1 + die2 int countSevens = 0; // the number of sevens rolled int rolls; // number of times to roll the dice console.put("Enter the number of rolls: "); rolls = console.getInt(); for (int i=0; i < rolls; i++) { die1 = 1 + (int)(Math.random() * 6); die2 = 1 + (int)(Math.random() * 6); total = die1 + die2; if (total == 7) countSevens++; } console.putln("The number of sevens was " + countSevens); } } // end of class Count Sevens
Question 5: Show the exact output produced by the following program:
class Example { public static void main(String[] args) { Console console = new Console(); int x = 1; int y = 10; do { int z = x*y; console.putln(z); x++; y--; } while (x < y); } // end of main } // end of program ExampleAnswer: Each execution of the loop produces a line of output containing one number. The first time through the loop, x is 1, y is 10, and so z is 10. Then x is incremented to 2, y is decremented to 9, and the loop repeats. This time, the output is 2*9, or 18. This continues until x becomes 6 and y becomes 5. So the output is:
10 18 24 28 30
Question 6: Write a for statement that will compute the sum of the first 100 integers, that is, 1*1 + 2*2 + 3*3 + ... + 100*100. You should not write a complete program, but you should declare any variables that you use.
Answer:
int sum = 0; // the sum of all the squares for (int N = 1; N <= 0; N++) sum += N*N;
Question 7: Recall from Section 2.8 that if str is a variable of type String, then str.length() is the length of the string (that is, the number of characters that it contains), and that str.charAt(N) is the character at position N in the string (where positions are numbered starting from zero). Write a Java program segment that will read in a string typed by the user and will print out a reversed copy of that string. For example, if the user types the string "Hello Java", then the computer should respond with "avaJ olleH". You can assume that a Console object named console has already been created.
Answer: Note that if length is the length of a string, then the characters in that string are numbered 0,1,2,...,length-1. The last character is in position number length-1, not in position number length.
String answer; // string typed in by the user console.putln("Please enter a string: "); answer = console.getln(); int length = answer.length(); for (int N = length-1; N >= 0; N--) console.put(answer.charAt(N)); console.putln();
Question 8: Explain what is meant by the "type" of a variable. Explain why types are necessary. And list at least four different types that can be used in Java programs.
Answer: Every variable has a type, which determines the set of possible values that it can hold. For example, if a variable is of type int, then it can hold whole numbers between -231 and +231-1. And a variable of type boolean can only hold the two logical values true and false. Other types in Java include double, char, long, and String. Types are necessary because what is actually stored in memory is binary numbers consisting of zeros and ones. Values of any type are "encoded" into binary numbers. The computer has to keep track of the type of a variable so that it knows how to "decode" the coded binary numbers that are stored in the variables.
Question 9: What are "parameters" and how are they used? Give an example.
Answer: Parameters are used for communication between a subroutine and the rest of the program. A parameter provides a value to be used in the computation performed by the subroutine. There are two types of parameters: formal parameters, which are names used in the definitions of subroutines, and actual parameters, which are the values provided when the subroutine is called. For example, in the subroutine definition
static double pythagorus(double x, double y) { return Math.sqrt(x*x + y*y); }x and y are formal parameters. When the subroutine is called in the statement:
hypotenuse = pythagorus(opp,adj);opp and adj are actual parameters.
Question 10: The hard part of programming is to create an algorithm for performing a given task. Discuss how "top-down design" and "step-wise refinement" can be used to help in the creation of algorithms. Also discuss how "subroutines" fit into the process.
Answer: Top-down design refers to breaking a problem down into subproblems, which can then be further broken down if necessary until eventually you come to problems that you know how to solve. Step-wise refinement is one way of going about top-down design. In step-wise refinement, you start with a general outline of an algorithm. This outline is refined in a series of stages, where each stage adds more detail. This continues until you have a complete algorithm in which each step can be translated into programming language.
Subroutines fit into this process in two ways. First, when you divide a problem into subproblems, you can write a subroutine to solve each problem. Second, if you come to some subproblem, and you already have a subroutine to solve that problem, you don't have to solve it again. You can just use the subroutine that you already have.
David Eck