CPSC 124, Spring 2013
Sample Answers to Quiz #4

Question 1. Explain the purpose of the break statement in Java.

Answer. A break statement can occur inside a loop. When the break statement is executed, the loop that contains the statement ends immediately, and the computer jumps to the statement that follows the loop. Break can be used in both for loops and while loops. [Note: Break is also used in switch statements. A break statement in a switch ends the switch statement.]

Question 2. Suppose that str is a variable of type String. Explain the purpose of the following code segment:

    int i;
    for ( i = 0; i < str.length(); i++ ) {
        if ( str.charAt(i) != ' ' ) {
            System.out.print( str.charAt(i) );
        }
    }
    System.out.println();

Answer. This prints the string with any spaces that occur in the string omitted. For example, if the string is "Seize the day", then the output of this code segment will be: Seizetheday

Question 3. Write a for loop that will print out all the multiples of 3 from 3 to 99. That is, the output of the loop should be the numbers

      3 6 9 12 15 18 ... 96 99

You should output all the numbers on the same line, separated by spaces.

Answer.Here are three possible answers:


      int n;
      for ( n = 3; n < 100; n = n + 3 ) {
          System.out.print(n + " ");
      }
      System.out.println();

      int k;
      for ( k = 1; k <= 33; k++ ) {
          System.out.print( 3*k );
          System.out.print(" ");
      }
      System.out.println();

      int i;
      for ( i = 1; i <= 99; i = i + 1 ) {
          if ( i % 3 == 0 ) {  // test if i is divisible by 3
             System.out.print(i + " " );
          }
      }
      System.out.println();