CPSC 124, Spring 2013
Sample Answers to the First Test
Question 1. Briefly explain the difference between high-level languages and machine language.
Answer. Both are programming languages. However, in machine language, binary numbers are used to encode instructions that can be executed directly by the computer. High-level language, on the other hand, is somewhat closer in structure to a human language like English, but it must be translated into machine language by a compiler before it can be executed by the computer. People use high-level language when they write programs; computers use machine language when they execute programs.
Question 2. Variables in Java must be declared before they are used. What does a variable declaration statement do? Explain how your answer applies to the examples shown below. (In particular, be sure to explain the meaning of the words int, char, and String.)
int a, b; char firstLetter; String response;
Answer. A declaration is required before a variable can be used in a program. A variable is a name for a memory location in which a value can be stored. A given variable can hold only one type of value. The declaration creates the variable -- that is, it allocates memory for the variable and associates the variable's name with that memory location. It also tells the computer what type of value the variable can hold. In the examples, variables named a, b, firstLetter, and response are created. Their types are given as int, char, and String. An int variable can hold a 32-bit integer value. A char variable can hold a single character. A String can hold a sequence of zero or more characters.
Question 3. Style is an aspect of programming that is completely ignored by the computer. Explain what is meant by programming style and why it is important, and give a few rules of good style for programming in Java.
Answer. Programming style refers to aspects of programming that are completely ignored by the computer but that are important for human programmers. Good style makes it easier to read a program and to understand what it does and how it works. A program that follows the rules of good style will be easier to debug and will be easier to change in the future if necessary. The three most important style rules that we have encountered so far are probably: comment your code, indent your code to show the structure of the program, and use meaningful names for classes and variables.
Comments are used to describe the purpose of a program or variable. They should help a reader understand what a program does and how to use it. They should explain what a variable represents. Some comments might also be necessary to explain the detailed logic of the program code. Indentation means that the content of a class, subroutine, or control structure should be indented, so that it is possible to easily see where it begins and ends. Meaningful names can make it much easier to follow what is being done in complex code, which might otherwise look like meaningless symbol manipulation.
Question 4. Show the exact output produced by the following Java code segment:
int n, x, y; x = 1; y = 5; while ( x < y ) { x = x*3; y = y*2; n = y / x; System.out.println(n + "," + x + "," + y); }
Answer.
3,3,10 2,9,20 1,27,40 0,81,80
(On each line, x is 3 times its previous value, and y is 2 times its previous value. The value of n is computes as y/x. Since x and y are variables of type int, this is integer division, and the result is an integer -- the whole number of times that x goes into y. The loop ends after printing the last line shown; after printing that line, the while loop test, x <y, is no longer true and the loop ends.)
Question 5. Consider the following paintComponent() subroutine. Assume that the drawing area is 800 pixels wide and 600 pixels high, as usual. Make a table to show all the values that the variables x and y will have, and then draw the picture that would be produced when the subroutine is executed.
public void paintComponent(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0,0,800,600); g.setColor(Color.BLACK); int x,y; x = 200; for ( y = 100; y <= 500; y = y + 100 ) { g.drawLine( 100, y, x, y ); if ( y < 300 ) { x = x + 200; } else { x = x - 200; } } }
Answer. The values of x and y are
x | y ------|------ 200 | 100 400 | 200 600 | 300 400 | 400 200 | 500
In fact, y goes on to become 600, but the loop ends immediately after that, so x never gets a corresponding value and no line is drawn for y = 600. Note that the value used in the test "if ( y < 300 )" is the current value of y when the test is made. This is the value shown on the previous line of the table. When the picture is drawn, you get 5 horizontal lines, one for each line of the table. The endpoints of the lines are (100,y) and (x,y). The picture looks like this:
Question 6. Suppose that str is a String. Write a for loop that will print out all the characters from the string, with each character on a separate line of output.
Answer.
int i; for ( i = 0; < str.length(); i++ ) { System.out.println( str.charAt(i) ); }
Question 7. a) Write a complete Java program, starting with "public class...", that does the following: The program asks the user what the current temperature is, and it reads the user's response. (Assume that the temperature is an int.) Then the computer should output one of the three strings "That's cold!", "That's hot", or "That's nice!". Say it's hot if the temperature is above 85, it's cold if the temperature is less than 50, and otherwise it's nice.
b) Once you have typed the program into a file, what two commands do you need to use to get the computer to execute your program? (Give the complete commands as you would type them, not just the first word of each command.)
Answer.
a)
public class WeatherChat { public static void main(String[] args) { int temp; // The temperature, to be input by the user. System.out.print("What's the current temperature? "); temp = TextIO.getlnInt(); if (temp > 85) { System.out.println( "That's hot! "); } else if (temp < 50) { System.out.println( "That's cold!" ); } else { System.out.println( "That's nice!" ); } } }
b)
javac WeatherChat.java java WeatherChat
(The file name that is used in these commands must be the same as the name of the class in the program.)
Question 8. Define the term algorithm.
Answer. An algorithm is an unambiguous, step-by-step procedure for solving some problem, which is guaranteed to complete after a finite number of steps.
Question 9. Define the term exception, as it relates to Java programming.
Answer. An exception is an error, or other special condition, that occurs at run time and will cause the program to crash, unless the exception is "caught."
Question 10. Recall that Math.random() is a function that returns a random double value between 0 and 1. If you keep making such random numbers and adding them up, eventually, the sum will be bigger than 1000. Write a Java code segment that generates random numbers and adds them to a sum, stopping when the sum becomes greater than 1000. Count the numbers as you generate them, and output the count at the end. For example, the output might say, "It took 2017 random numbers to reach 1000." (Do not write a complete program, just the code that you need to complete the task.)
Answer.
double sum; // The running sum of the random numbers. int count; // The number of random numbers that have been used. sum = 0; count = 0; while ( sum <= 1000 ) { sum = sum + Math.random(); count++; } System.out.println("It took " + count + " random numbers to add up to 1000.");
Note: It's actually possible to do this with a for loop, though not a basic counting for loop. The sum is used as the for-loop variable, and the update operation for this variable is sum = sum + Math.random(). Some students did it this way:
double sum; // The running sum of the random numbers. int count; // The number of random numbers that have been used. count = 0; for ( sum = 0; sum <= 1000; sum = sum + Math.random() ) { count++; } System.out.println("It took " + count + " random numbers to add up to 1000.");