## CPSC 124, Spring 2014 Sample Answers to Quiz #3

Question 1. What is meant by an infinite loop, and why is it usually a bad thing?

Answer. An infinite loop is a loop that never ends, because the condition that would end the loop is never satisfied. This is usually bad because an infinite loop will make a program run without ending (unless it is killed, such as by typing a Control-C). The program will never produce a result or, alternatively, will produce an unending stream of output.

Question 2. Briefly state the meaning of each of the following operators:

```        %

++

&&
```

```        %   Computes the remainder when one integer is divided by another integer.

++  When applied to a variable, adds 1 to its value;
As a statement,  x++;  has the same effect as  x = x + 1;

&&  A boolean operation meaning "and".  For boolean values p and q,
p && q is true if and only if both p and q are true.
```

Question 3. Write a code segment that prints out the message "Hello World" 42 times. Use a while loop.

```      int count;
count = 0;
while (count < 42) {
System.out.println("Hello World");
count = count + 1;
}
```

Question 4. Complete the following program so that it asks the user to enter an integer, reads the user's response, and then tells the user whether the integer is even or is odd. (Recall: The value of n%2 is 0 if and only if the integer n is even.)

```      public class OddOrEven {
public static void main(String[] args) {

}
}
```

```      public class OddOrEven {
public static void main(String[] args) {
int number;
System.out.print("Enter an integer: ");
number = TextIO.getlnInt();
if ( number % 2 == 0 ) {
System.out.println(number + " is an even integer.");
}
else {
System.out.println(number + " is an odd integer.");
}
}
}
```