Practice Questions: Week 02


Using Primitive Types

1. Write a program that reads in an integer number between 2 and 9 inclusive from the command line. Your program should multiply the number by 9 to get a two digit number. Your program should then sum the two individual digits and output the sum.


2. Write a program that reads in a three digit integer number (i.e., any integer from 100 to 999) and outputs the sum of the digits.


3. Requires Math.sqrt. 3D computer graphics makes extensive use of three-dimensional vectors. A very common operation is to normalize a vector so that its magnitude is 1; this is accomplished by finding the length of the vector and then dividing each component of the vector by the length. For example, to normalize the vector [1.5 0.3 2.4] we:

  1. find its length = sqrt(1.5 * 1.5 + 0.3 * 0.3 + 2.4 * 2.4)
  2. divide each component [1.5 0.3 2.4] by the length

Write a Java program that reads three real numbers representing a 3D vector from the command line and outputs the normalized vector.


4. Another common operation in 3D graphics is the dot product of two three-dimensional vectors. The dot product of two vectors [u v w] and [x y z] is the real number u * x + v * y + w * z.

Write a Java program that reads six real numbers representing two 3D vectors from the command line and outputs their dot product. What is the dot product of two perpendicular vectors?


5. Write a program that computes the sum of the three mathematical constants π, e, and φ (φ is the golden ratio) and outputs the two integers that the sum lies between.


6. Write a program that reads a positive integer from the command line and outputs the number rounded to the nearest multiple of 5. For example, 17 rounded to the nearest multiple of 5 is 15, and 18 rounded to the nearest multiple of 5 is 20. Your program should only use int arithmetic to perform the rounding.


7. See Question 6 first. There has been discussion about removing the Canadian penny from circulation, as it may cost more to manufacture a penny than it is worth. If this happens then cash prices will need to be converted to multiples of 5 cents. Write a program that reads a positive real number with two digits after the decimal from the command line representing the cost of an item in dollars and cents. Your program should output the cost (also with two digits after the decimal) rounded to the nearest five cents.

See the Wikipedia article about abolishing the penny and how the Swedes converted monetary amounts to 5 cent intervals.


8. eCheck 01B


9. eCheck 01D