CPSC 124, Spring 2017: Sample Answers to Quiz #3

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

Question 1. Show the exact output from this code segment:

               String text;
               char ch;
               text = "Now is the time";
               for (int i = 0; i < text.length(); i++) {
                    ch = text.charAt(i);
                    if ( ch == ' ' ) {
                        System.out.println();
                    }
                    else {
                        System.out.print( ch );
                    }
                }

Answer. When the if statement encounters a space character in the string, it outputs a new line character by calling System.out.println(). If the character is not a space, it outputs the character without a new line by using print instead of println. The output is on the same line, except when there is a space, which starts a new line. This means that the individual words from the string are on separate lines. The output is:

              Now
              is
              the
              time

Question 2. Explain the break statement. (Where can it be used? What does it do.)

Answer. A break statement consists of the single word break, followed by a semicolon. It can be used inside a loop. When a break statement is executed in a loop, the effect is to end the loop immediately and to jump to the next statement that comes after the loop. Usually, break is used in an if statement and is only executed when the test in the if is true. This makes it possible to test a condition for ending the loop in the middle of the loop rather than at the start of the loop. One use of this is to break out of a "while(true)" loop.

Question 3. Write a code segment that will print out all of the even numbers from 2 to 100, with one number on each line of output. (That is, the code should print the numbers 2, 4, 6, 8, 10, ..., 98, 100.) Use a loop; either a for loop or a while loop is acceptable.

Answer. There are many ways to do this. Here are a few....

                 for (int num = 2; num <= 100; num = num + 2) {
                     System.out.println(num);
                 }
                 
                 
                 for (int x = 1; x <= 100; x++) {
                     if ( x % 2 == 0 ) {
                         System.out.println(x);
                     }
                 }
                 
                 
                 for (int i = 1; i <= 50; i++) {
                     System.out.println( 2*i );
                 }