CSE 131 Quiz 1 Makeup Solutions Data Types and Expressions 28 Feb 2011 1. (60 points) Complete the following table by filling in the value and type of each expression. Assume that variables i and x have been declared and initialized by the statements shown below. int i = 13; double x = 27.2 Expression Value Type 2 + 2.0 4.0 double 11/3 3 int 2*3 + “9” + (5 - 2) “693” String x /2 == i false boolean (x < 23) && (i < 7) || (i < x) true boolean 5 * 3 / 2 == 5 * (3 / 2) false boolean 2.0 * (++i ) 28.0 double 2. (40 points) The following method is supposed to return the sum of the integers from m through n (so, sumRange(2,4) should equal 2+3+4=9). It is based on the fact that 1+2+...+n = (1/2)n(n+1). Assume 0 < m n. public static int sumRange (int m, int n) { return (n/2)*(n+1) - (m/2)*(m-1); } a. What are the input types for this method (i.e., what are the types of the formal parameters)? (10 pts)) int b. What value is returned by the method when it is called with arguments 3 and 5? (10 pts) (5/2)*6 - (3/2)*2 = 12 - 2 = 10 c. Show how to re-write the return statement, so that the method always returns the correct result. Your solution should use only integer arithmetic (no type conversions) and should not use either iteration or recursion. Hint: the product of any two consecutive integers is an even number. return n*(n+1)/2 - m*(m-1)/2;
© Copyright 2024 Paperzz