CPSC 124, Fall 2017: Sample Answers to Test #1

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. Explain the difference between a machine language and a high-level programming language and the relationship between them. (How does this relate to javac?)

Answer. "Machine language" refers to the set of instructions, encoded as binary numbers, that the CPU of a computer can execute directly. In a "High Level Programming Language," instructions are written in a form that is closer to human language and easier for people to write and to understand. However, a program written in a high-level language must be translated into machine language before the computer can execute it. The translation can be done by a compiler or an interpreter. In the case of the high level language Java, the javac command is used to run the Java compiler on a program written in Java. (This translates the Java code into the machine language of the "Java Virtual Machine", which can then be interpreted by the java command.)

Question 2. Assume x and y are variables of type double that already have values. Write a short code segment that prints out the value of .

Answer.

System.out.println( Math.sqrt( x*x + y*y ) );

Question 3. Write a code segment that simulates rolling a die until a six is rolled, and at the end prints out the number of rolls. (Rolling a die means picking a random integer in the range 1 to 6, inclusive.) Use a while loop (or a do..while loop if you prefer).

Answer. Here are four possible solutions:

(1)     int die;
        int count;
        count = 0;
        while (true) {
           die = (int)( 6*Math.random() + 1 );
           count++;
           if (die == 6) {
              break;
           }
        }
        System.out.println( count + " rolls to get a 6" );
         
         
(2)     int die;
        int count;
        die = (int)( 6*Math.random() ) + 1;
        count = 1;  // count the first roll!
        while ( die != 6 ) {
            die = (int)( 6*Math.random() ) + 1;
            count = count + 1;
        }
        System.out.println( count + " rolls to get a 6" );
        

(3)     int die;
        int count;
        count = 0;
        do {
            die = (int)( 6*Math.random() ) + 1;
            count += 1;
        } while ( die != 6 );
        System.out.printf( "It took %d rolls to get a six.%n", count );
        
        
(4)     int die;
        int count;
        die = 0;  // prime the loop
        count = 0;
        while ( die != 6 ) {
            die = (int)( 6*Math.random() + 1 );
            ++count;
        }
        System.out.printf( "It took %d rolls to get a six.%n", count );

Question 4. Show the exact output from the following code segment:

int n;
n = 100;
while ( n > 1 ) {
    n = n / 2;
    System.out.printf( "n = %2d", n);
    System.out.println();
}
System.out.println("DONE");

Answer.

    n = 50
    n = 25
    n = 12
    n =  6
    n =  3
    n =  1
    DONE

(One thing to note is that n is always an integer, so that, for example, when n is 25, n/2 is 12, not 12.5. Also, the value n = 1 appears at the end of the output, since it is printed before the test n>1 is made for the last time. Finally, to account for the "%2d" in the System.out.printf statement, the 6, 3, and 1 have to line up with the second digit of 50, 25, and 12.)

Question 5. Suppose that str is a variable of type String that already has a value. Write an if statement that will test whether the first character in str is equal to the last character in str, and output an appropriate message about the result of the test.

Answer.

if ( str.charAt(0) == str.charAt(str.length() - 1) ) {
    System.out.println("The first and last characters are THE SAME.");
}
else {
    System.out.println("The first and last characters are DIFFERENT.");
}

Question 6. In the preceding problem, suppose that str happens to be the empty string, which contains no characters. What will happen when the computer makes the test that is required in that problem?

Answer. The program would CRASH with an error when it tries to evaluate str.charAt(0), because the empty string does not have a character number zero.

Question 7. Suppose that numbers is an array of type double[], and that it has already been filled with numbers. Your goal is to compare the number of positive numbers in the array to the number of negative numbers in the array. Write a code segment that will count both the number of postive numbers (greater than zero) and the number of negative numbers (less than zero). After that, it should output one of the strings "More positive numbers", "More negative numbers", or "Equal numbers of positives and negatives".

Answer.

int countPos, countNeg;
countPos = 0;
countNeg = 0;
int index;
for ( index = 0; index < numbers.length; index++ ) {
    if ( numbers[index] > 0 ) {
        countPos = countPos + 1;
    }
    else if ( numbers[index] < 0 ){
        countNeg = countNeg + 1;
    }
}
if ( countPos > countNeg ) {
    System.out.println("More positive numbers");
}
else if ( countPos < countNeg ) {
    System.out.println("More negative numbers");
}
else {
    System.out.println("Equal numbers of positive and negative");
}

Question 8. Show the picture that is drawn by the following paintComponent() subroutine. Use the box at the right for the picture. Assume that the box represents a drawing area that is 800 pixels wide and 600 pixels high.

public void paintComponent( Graphics g ) {
    int i, j;
    j = 400;
    for ( i = 100; i < 600; i = i + 100 ) {
        g.drawLine( 100, i, j, i );
        if ( i < 300 ) {
             j = j + 100;
        } else {
             j = j - 100;
        }
    }
}

Answer.

(There are 5 lines, with i taking on the values 100, 200, 300, 400, and 500. The value of j is 400 for the first line, and i is 100. So, the first line extends from (100,100) to (100,400), which is a horizontal line in the left half of the box, 1/6 of the way from the top to the bottom. Each line is 100 pixels lower than the previous line. The lengths of the line increase by 100 after the first and second line (when i is less than 300), and decrease by 100 after the third and forth lines (when i is greater than or equal to 300).)

Question 9. Write a complete Java program (starting with "public class") that does the following: Ask the user to enter an integer, and use TextIO to read the user's response. Then print out "Hello World" that many times. That is, if the user's input is 42, the program should print "Hello World" 42 times. (You do not need to add any comments.)

Answer.

public class LotsOfHellos {
    
    public static void main(String[] args) {
        int numberOfHellos;
        int count;
        System.out.print("How many hellos do you want? ");
        numberOfHellos = TextIO.getlnInt();
        for ( count = 0; count < numberOfHellos; count++ ) {
            System.out.println("Hello World");
        }
    }

}

Question 10. Algorithms are a central concern of computer science. Give a careful, exact definition of the term algorithm, and then explain how algorithms relate to computer programs.

Answer. An algorithm is just an unambiguous, step-by-step procedure for performing some task that is guaranteed to terminate after a finite number of steps.

An algorithm is not the same as a program, because an algorithm doesn't have to be written in a programming language. (It doesn't even have to be something that can be done by a computer.) However, an algorithm can be expressed as a computer program. The algorithm is the idea behind the program, not the program itself.

Question 11. Syntax, semantics, and style are three terms related to computer programming. Write an essay that discusses each term, explaining its meaning and why it is important. Examples would be useful.

Answer. In the context of this course, syntax, semantics, and style all refer to properties of computer programs.

Syntax refers to the grammar of the programming language. It tells you exactly what can and cannot be legally written in a program. Correct syntax is important because a program that does not follow correct syntax cannot even be compiled. In Java, for example, a variable must be declared before it can be used. If you don't do so, the compiler will report an error and refuse to compile the program.

Semantics refers to the meaning of a program. The semantics of the statement "y = x + 7;" is that when the computer executes this statement, it will fetch the value of the variable x, add 7 to that value, and store the result into the variable y. Semantics is important because it tells you what the program will actually do when it is run. You need to understand the semantics of the language in order to understand how to write a program to do what you want it to do.

Style refers to aspects of a program that are completely irrelevant to the computer. It refers to things like layout, commenting, and variable nameing. Style does not affect whether a program can be compiled or what it will do when it is run. However, style is important because good style makes it easier for people to read and understand the program. For example, using indentation makes the logical structure of the program more apparent to a reader. Adding comments to a program can help a reader understand what the program is supposed to do and how it does it. Following the rule that a variable name should begin with a lower case letter makes it easy to tell at a glance whether a given identifier is a variable or is the name of a class.