COSC 135B Exam 2 Practice Problems
Tom Linton, Fall 2000, Central College
  1. Write four different Java statements that each add 1 to integer variable x.
  2. Write Java statements to accomplish each of the following:
    1. Assign the sum of x and y to z and increment the value of x by 1 after the calculation. Use only one statement.
    2. Test if the value of the variable count is greater than 10. If it is, print "Count is greater than 10".
    3. Decrement the variable x by 1, then subtract it from the variable total. Use only one statement.
    4. Calculate the remainder after q is divided by divisor and assign the result to q. Write this statement two different ways.
  3. Determine the values of each variable after the calculation is performed. Assume that when each statement begins executing, all variables are integers, product = 5, x = 3, and quotient = 100.
    1. product *= x++;
    2. quotient /= ++x;
  4. What does the following code fragment print in the TextArea named output?

  5.      int y, x = 1, total = 0;
         while ( x <= 4 ) {
            y = x * x;
            output.append( " " + y-- );
            total += y;
            x++;
         }
         output.append( "\nTotal is " + total );
  6. Write a for loop that prints the following table of values (including the header rows) in the TextArea named output:
N N^2 N^3
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
  1. Note that if the variable someString is a String, the Java statement someString += "more stuff"; is equivalent to the Java statement someString = someString + "more stuff";  Use this fact to complete the for loop below, which is suppose to print all of the integers from 1 to 100 that are multiples of 2 or multiples of 5.
    1. String answer = "2";
      for ( int k = 3; ???; k++) {
          if (    )
              answer += ", " + k;
      }
      System.out.println(answer);
  2. Assume that output is a TextArea. What is displayed by the following code fragment?
    1. int row = 4, column;
      output.setText("");//erase any text
      while ( row >= 1 ) {
         column = 1;
         for (column = 1; column <= 5; column++ ) {
            if ( row % 2 == 1 )
               output.append( "<" );
            else
               output.append( ">" );
         }
         row--;
         output.append("\n");
      }
  3. Determine the output for each of the following when x is 9 and y is 11 and again when x is 11 and y is 9. Note that the compiler ignores the indentation in a Java program. Also, the Java compiler always associates an else with the previous if unless told to do otherwise by the placement of braces ({}). Because, on first glance, the programmer may not be sure which if an else matches, this is referred to as the "dangling-else" problem. I have eliminated the indentation from the following code to make the problem more challenging. Hint: Apply indentation conventions you have learned.
    1. if ( x < 10 )

    2. if ( y > 10 )
      System.out.println( "*****" );
      else
      System.out.println( "#####" );
      System.out.println( "$$$$$" );
    3. if ( x < 10 ) {

    4. if ( y > 10 )
      System.out.println( "*****" );
      }
      else {
      System.out.println( "#####" );
      System.out.println( "$$$$$" );
      }
  4. Modify the following code to produce the output shown. Use proper indentation techniques. You may not make any changes other than inserting braces ( "{" and "}" ) and changing the indentation of the code. The compiler ignores indentation in a Java program. I have eliminated the indentation from the following code to make the problem more challenging. Note: It is possible that no modification is necessary.
    1. if ( y == 8 )
      if ( x == 5 )
      System.out.println( "@@@@@" );
      else
      System.out.println( "#####" );
      System.out.println( "$$$$$" );
      System.out.println( "&&&&&" );
    2. Assuming x = 5 and y = 8, the following output is produced:

    3. @@@@@
      $$$$$
      &&&&&
       

    4. Assuming x = 5 and y = 8, the following output is produced:

    5. @@@@@
       

    6. Assuming x = 5 and y = 8, the following output is produced:

    7. @@@@@
      &&&&&
       

    8. Assuming x = 5 and y = 7, the following output is produced. Note: The last three output statements after the else are all part of a compound statement.

    9. #####
      $$$$$
      &&&&&

  5. Consider the problem of writing a Java program to draw the figure below. Note: Each row of this figure is 5 characters wide, and contains 1, 3 or 5 asterisks in the center. There are 9 rows in the figure.
*
***
*****
*
*
*
*
*
*
    1. Define a method named makeStars( ), which has as input a single integer, say numStars, and returns a String that is 5 characters wide and contains numStars many asterisks in its center. For example, makeStars(3) should return the String " *** ". If you use Format.justify in your method, you will avoid some subtle problems, such as whether makeStars(4) should be " ****" or "**** ". If the input is larger than 5, or less than zero, your method should return the String "error".
    2. Assuming that your makeStars method is defined and that output is a TextArea, complete the following code fragment so that it draws the arrow above. Each (non-empty) case in your switch block MUST have the form:
      1. output.append( makeStars(x) + "\n" );
        break;
      for some value of x (an integer). Here is the start of your arrow drawing code fragment:
       
        output.setText("");//erase the old text
        for (int row = 1; ???; ???) {
           switch(row) {
              case ?
              ?



           }// end switch
        }// end for loop
  1. A company wants to transmit data over the telephone, but they are concerned that their phones may be tapped. All of their data is transmitted as four-digit integers. They have asked you to write a method, named encrypt, that will encrypt (encode) a single four-digit integer so that it may be transmitted more securely. Your method should have one (four-digit or less) integer input and return the encrypted integer, which is defined as follows:
  2. Write a separate method named decrypt. that inputs an encrypted four-digit integer and returns the decrypted version (i.e the input is a coded number and the output is the original number). For both methods, you should check to insure that the inputs are not more than 4 digits long (think about integer division by 1000 or 10000 to complete this test). If they are, return the value -1 (a common programming technique is to return -1, when outputs should be positive, to indicate an error).
  3. What is returned by (double) (3 / 4);        how about (double) 3 / 4; explain.
  4. In Java, how do you say "if N is negative or N is even, add 5 to N, otherwise decrease N by 1"?
  5. The following code is neither intuitive nor well designed, but contains many of the constructs we've studied. To the best of your ability, trace the flow of the following code. That is, walk through the commands which Java executes, in the order that Java executes them, keeping track of the values of the variables. Hint: create a table showing the value of each data field or variable as you go through the program. Assume that the GUI is defined, that results is a TextArea, and trace what happens as the user clicks the button.
    1.  
      public class TraceMe extends GBFrame {
     
      public static int methodA(int x) {
            if (x > 5)
               return (x-4);
            else
               return (x+2);
         } // end methodA

         public static void buttonClicked(Button myButton) {
            int n = 4;
            int x = 6;
            while (n > 0) {
                switch (x) {
                   case 1:
                      n *= 3;
                      break;
                   case 3:
                      n -= 6;
                      break;
                   default:
                      n++;
                      break;
                }//end switch
                x = methodA(n);
                results.append("x= " + x + " and n = " + n);
            }// end while
          } // end buttonClicked

       } // end TraceMe

  6. Write a method named isLessThan that takes two inputs, x and y, and returns true when x < y, and false when x >= y.
  7. Assuming the following definition of the method scramble:

  8. public static int scramble(int egg)

       egg = (egg * 35) % 4;
       return egg;
    }

    what are the final values of the variables liquid and yolk, after the following lines of code are executed?

       int liquid, yolk = 5;
       liquid = scramble(yolk);