CPSC 124, Spring 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. Define each of the following terms, as it pertains to this course:

a)  algorithm
b)  infinite loop
c)  machine language

Answer.

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

b)  An infinite loop is a loop, such as while loop, that never ends because the condition for exiting the loop never becomes true.

c)  The machine language of a computer is the programming language in which instructions are encoded as binary numbers that can be executed directly by the hardware of the computers. Programs written in other languages must be translated into machine language before they can be executed.

Question 2. Price of admission to a museum depends on the age of the customer: The price is $3 if the age is less than 13; $7 if the age is greater than 64; and $10 otherwise. Write a code segment that asks the user for their age, reads the user's response, and then tells them their price of admission to the museum.

Answer.

             int age;
             int price;
             System.out.print("What is your age? ");
             age = TextIO.getlnInt();
             if ( age < 13 ) {
                 price = 3;
             }
             else if ( age > 64 ) {
                 price = 7;
             }
             else {
                 price = 10;
             }
             System.out.println("Your price is $" + price);

Question 3. Suppose that str is a variable of type String. Write a code segment that will count the number of times that the character 'e' occurs in the string. (Use a loop to go through all the characters in str, and compare each one to 'e'.)

Answer.

            int countE; 
            countE = 0;
            for ( int i = 0; i < str.length(); i++ ) {
                if ( str.charAt(i) == 'e' ) {
                    countE = countE + 1;
                }
            }
            // countE is equal to the number of e's in str

Question 4. Complete the following paintComponent subroutine so that it will draw the picture shown below. Use a for loop. There are exactly 11 lines in the picture. The scale that you use is up to you, but your picture should have the same form as the one that is shown. (You do not have to fill in the background or set the drawing color. Just draw the lines.)

Answer. My answer assumes that the picture is 5o pixels tall, and the y-coordinate at the top is 10. The bottom endpoints of the lines are separated by 10 pixels, and the first bottom endpoint has x-coordinate 10. We need to know the x-coordinate of the point at the top. It is above the fifth bottom endpoint, which will have x-coordinate 10+(5*10), or 60.

       First solution:
       
             for ( int x = 10; x <= 110; x = x + 10 ) {
                 g.drawLine( 60, 10, x, 60 );
             }
             
             
       Second solution:
       
             int x;
             x = 10;
             for (int i = 1; i <= 11; i++ ) {
                 g.drawline( 60, 10, x, 60 );
                 x = x + 10;
             }

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

              int a, b, c;
              a = 1;
              b = 2;
              c = 6;
              while (c > 0) {
                 if ( c % 2 == 1 ) {
                    a = a * b;
                 }
                 b = b * b;
                 c = c / 2;
                 System.out.println( a + "," + b + "," + c);
              }

Answer. The first time through the loop, c is 6, and c % 2 is zero, so the value of a does not change; b is squared, so its new value is 4; c is divided by 2, so its new value is 3. The first line of output is "1,4,3". The second time through the loop, c % 2 is 1, and the line a = a * b assigns 4 to a; the values of b and c are changed to 16 and 1. The output is "4,16,1". Finally, the third time through the loop, c % 2 is again equal to 1, and the output is computed as "64,256,0". Since c is now 0, the loop ends. (Remember that c / 2 does integer division, discarding the remainder.) The complete output is:

           1,4,3
           4,16,1
           64,256,0

Question 6. You want to get an integer from the user that is in the range 1 to 10. Write a code segment that will do this. Use a loop to ask the user for a number in the range 1 to 10, get the user's response, and repeat until the number is actually in the correct range.

Answer.

           int num;
           while (true) {
               System.out.print("Enter an integer in the range 1 to 10:  ");
               num = TextIO.getlnInt();
               if ( num >= 1 && num <= 10 ) {
                   break;
               }
               System.out.println("That number is not in the specified range.");
           }
           // At this point, num must satisfy num >= 1 and num <= 10

Question 7. Suppose that numbers is an array of integers. (That is, it was declared to have type int[].) Assume that the array has already been created and filled with values.

a)  Write a loop that will print out all the elements of the array, numbers, with one number per line.

b)  Write a code segment that will determine whether there is a 42 in the array. If there is, print "yes"; otherwise print "no". (Make sure that you print just one line of output. Suggestion: use a boolean variable.)

Answer.

             a)    for (int i = 0; i < numbers.length; i++) {
                         System.out.println( numbers[i] );
                   }
                   
                   
             b)    boolean found42; 
                   found42 = false; // Will be set to true if a 42 is found.
                   for  (int i = 0; i < numbers.length; i++) {
                       if ( numbers[i] == 42 ) {
                           found42 = true;  // Got it!
                           break;
                       }
                   }
                   if ( found42 ) {
                        System.out.println("yes");
                   }
                   else {
                        System.out.println("no");
                   }
                   // The break is not strictly necessary, but
                   //   it makes the code more efficient.

Question 8. Explain carefully what is done by the following statements:

                double[] guess;
                guess = new double[1000];

Answer. The first line creates a variable named guess that can refer to an array of double values; it does not create an actual array. The second line creates an array that holds 1000 double value and sets guess to refer to that array. After this, the array elements guess[0], guess[1], ..., guess[999] all exist.

Question 9. What are all the possible outputs from the following statement? Why?

               System.out.println( 3 + (int)(5 * Math.random()) );

Answer. The possible outputs are 3, 4, 5, 6, and 7. The value of 5*Math.random() is between 0 and 5, but always strictly less than 5. When that value is type-case to int, the fractional part of the value is discarded (that is, the number is rounded down to the nearest integers), so the value must be 0, 1, 2, 3, or 4. Finally, 3 is added to the value, giving 3, 4, 5, 6, or 7.

Question 10. "Style" in a computer program is completely ignored by the computer. Nevertheless, programming style rules are important. Write a short essay that explains what is meant here by style and why style is important. Also state at least two style rules and explain why it is a good idea to follow each rule.

Answer. Style is ignored by the computer, but it is very important for human readers. Good programming style makes it easier for people to read and understand the program. This is helpful when you are writing the program, and it is very important if you want to share the program source code with other people. It will make it easier for them to understand the program. It will make it easier for them (or you) to modify the program in the future.

Some some style rules include: Use indentation to make the structure of the program clear; this makes it easier to understand where control structures begin and end. Use comments to explain the logic of the program, when it is not clear; this helps readers to understand the code without having to decipher all the details. Follow the naming convention for variables (start with lower case letter, and capitalize embedded words; this makes it easier to remember the proper case when you use the variable. Use meaningful variable names; this makes the intent of the code that uses the variables more meaningful to a human reader.