NAME
___________________________
Perm. no. _________________
 


CS 10: Introduction to Computer Programming

In-Class Examination 2

Closed-Book, 75 minutes, Winter 1998
 

General Instructions


Question  Value  Score
1  20   
2  20   
3  20   
4  20   
5 20  
Total 100   

1. Let a and b be int variables.  Translate the following nested if/else statement to an equivalent switch statement.   If this cannot be done, explain why.

2. Assume in the Java statements below that i, n, and sum are int variables.  Translate the Java statements below to an equivalent sequence of statements that uses neither break, continue, nor for statements.  If this cannot be done, explain why. 3. Convert the following sequence of Java statements to an equivalent single if/else statement.   If this cannot be done, explain why. 4.
  1. (15 points) A prime number is a positive integer such that the only positive integers that evenly divide it are 1 and itself.  The smallest prime is 2.  For example, 3 and 7 are prime numbers; 8 and 9 are not.  Define your own Java method, called prime, that returns true if its int argument, n, is a prime number.   It returns false otherwise.  You may assume that n is positive.  To get full credit, you must make use of the fact that if n is not prime, then there is some integer less than or equal to  the square root of n that evenly divides n.  For example, if n was 121, your method would not check for factors that are greater than 11.
  2. (5 points) Using the method called prime whose specification is given above, define your own Java method, called composite,  that returns true if and only if its int argument, n, is not prime.  You may assume that n is positive.
5. 
  1. (13 points) Define a method, called elementwiseSum, that has 3 int array parameters, called x, y, and z. The method does not return anything. For every element i of z, it puts the value of the ith element of x plus the value of the ith element of y into the ith element of z.  For a particular ith element of z, if there is no corresponding ith element of x or no ith element of y, then the ith element of z should be set to -1.  Ignore elements of x and/or y for which there is no corresponding element of z.
  2. (5 points) Give Java statements to declare an int array, a,  with 100 elements, an int array b with 200 elements, and an int array c with 50 elements.  For every element i of a, set the ith element of a to i.   Set each element of b to a random integer between -10 and 10, inclusive.
  3. (1 point) Give a Java statement that invokes method elementwiseSum with arrays a, b, and c.
  4. (1 point) Are the values of c changed by invoking elementwiseSum?