CPSC 124, Spring 2021:
Sample Answers to Quiz #4
These are sample answers only!
Question 1. The following code segment is supposed to get a number from the user and make absolutely sure that the input is one of the numbers 1, 2, 3, 4, 5. However, it doesn't work. Explain why it doesn't work and what small change needs to be made to fix the problem.
int N; N = TextIO.getlnInt(); System.out.print("Enter your number: "); if ( N < 1 || N > 5 ) { System.out.println("Please enter 1, 2, 3, 4, or 5!"); System.out.print("Enter your number: "); N = TextIO.getlnInt(); }
Answer.
The "if" statement should be a "while" statement. The problem is that the if statement
does not guarantee that the condition (N < 1 || N > 5)
is false after the if statement ends, since the user can enter another bad value inside the
if statement. A while statement guarantees that its condition is false after the loop
ends. In this case, that means that after the loop, N
is not less than 1 or greater
than 5, so it must be 1, 2, 3, 4, or 5.
Question 2. An array is a kind of data structure. Explain what is meant by an array.
Answer. An array is just a numbered sequence of elelemts. Each element holds a data value. An element can be referred to by its postion number in the list.
(In Java, all elements are of the same type, the length of the array is fixed, and numbering starts at zero, but these are not defining properties of arrays in general.)
Question 3. Show the output produced by the following code segment. (If your answer is incorrect, explaining your work might get you some partial credit.)
int i; int[] A; A = new int[6]; /* Fill the array */ A[0] = 1; for (i = 1; i < 6; i++) { A[i] = 1 + 2*A[i-1]; } /* Print the array */ for (i = 0; i < 6; i++) { System.out.println( A[i] ); }
Answer.
1 3 7 15 31 63
This code creates an array of ints with 6 elements named
A[0], A[1], A[2], A[3], A[4], and A[5]
. The number 1 is
stored explicitly in A[0]
. Then a for loop stores
values in the remaining elements. In the for loop, when i equals 1,
A[1]
is computed as 1+2*A[i-1]
, which is
1+2*A[0]
. Since A[0]
is 1, then
A[1]
is assigned the value 3. When i equals 2 in the
for loop, by the same reasoning, A[2]
is assigned
the value 1+2*3
, which is 7. In general, each element is
obtained by multiplying the previous element by 2 and adding 1.
The second for loop just prints out the elements in order, one
to a line.