CS 124, Fall 2009
Solutions to Quiz #3

1. Explain the meaning and purpose of the break statement in Java.

Answer: A break statement can be used to break out of a loop. That is, when a break statement is executed in the middle of a loop, the loop ends immediately (and the computer jumps to whatever statement follows the end of the loop).

2. In the context of programming, what is a bug, and what does it mean to debug a program?

Answer: A bug is an error. Specifically, it is a "semantic" error that occurs when the program is executed, and the program crashes or does not give the correct result. "Debugging" is the process of tracking down the bugs and modifying the program to eliminate them.

3. Write a code segment that uses a for loop to print out all the even integers from 2 to 100, with one number per line of output.

Answer: Here are three possible answers:

int num;
for (num = 2; num <= 100; num += 2) {
   System.out.println(num);
}


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


int ct;
for (ct = 1; ct <= 50; ct++) {
   System.out.println( 2*ct );
}

4. Show the exact output of the following code segment:

int x,y,z;
x = 2;
y = 5;
z = 1;
do {
     if ( y % 2 == 1 ) {
         z = z * x;
     }
     y = y / 2;
     x = x * x;
     System.out.printf("%4d%4d%4d", x, y, z);
     System.out.println();
} while (y > 0);

Answer: To solve this problem, you have to work through the program step-by-step, imitating the process that the computer goes through when it executes the code. Note that "if ( y % 2 == 1 )" tests whether y is and odd number and that "y = y / 2" does integer division, throwing away the remainder. The loop in this program segment is executed three times. Each execution produces one line of output. Because of the use of formatted output, the numbers are output in columns that are four characters wide. Here is the output, with "_" characters inserted in place of the blank spaces that are actually printed by the computer:

___4___3___2
__16___1___2
_256___0__32