2.7 Review Exercises

Exercise 2.7

  1. Evaluate. Use a decimal point in your answer if the result is double.
    a) 15 / 6 + 15 % 6   b) 3e-1 + 2e1
    c) 2 / 5 * 8.0       d) 1.6 * 20 % 8
    e) (double) (25/4)   f) (int) 2.7 + 6.3
    g) 20 - 10* (15%4)   h) 7/(-5) + 4%(-3)
    i) 2*3/(double)4     j) (int) 4.8 % 1.1
    k) 6 / 4 * 2         l)  2 * 3/2
    m) (int)2.7 * 1. 8   n) (int)2.7 * (int)1.8
    o) (int)(2.7*1.8)
    
    
  2. Each of the following expressions is intended to evaluate the expression.

    Some are correct while others are not. Classify each as being correct or incorrect. For those that are incorrect, give the reason(s).
    a) (a *x *x + b)/ ((c *x) + d)
    b) (a * pow(x,2) + b) / (c *x + d)
    c) ((a)(x)(x) + (b)) / ((c)(x) + d)
    d) (b + x * (x *(a))) / (d + x * (c))
    e) (a) * pow(x,2) + (b) / ((c) *(x) + d)
    f) (a *(x *x) + (b) / c *(x) + d
    
  3. Suppose that the following declarations have been made.
    int i = 3, j = 4, k = 2; 
    Using these starting values in each part, find the value of each variable after the given statement has been executed.
    
    a) j = ++i * k--; 	b) i = --j + k/2;
    c) k = i-- - j++; 	d) j = (2*i++)%(++k + 1);
    e) i += j -= --k; 	f) i *= j /= k++;
    
  4. State the value of each expression.
    a) (char)('b' + 6) 	b) (int)('M' - 'T')
    
  5. Evaluate.
    a) round(sqrt(20))
    b) sqrt(abs(-49))
    c) (int)random(1)
    d) pow(0.5,-4)
    
  6. Write as Processing expressions.

  7. Rewrite the statement

       m = n-- * ++p;
    using three statements.

  8. To switch the values contained in the variables x and y, a programmer wrote the following segment:
    x = y;
    y = x;
    
    
    (a) If, before execution of the segment, x contained the value 7 and y contained the value 4, what value would each have after the segment was performed?

    (b) Rewrite the segment so that it performs the intended task correctly.

  9. Write a program that reads three float values and computes their mean, rounded to two decimal places.

  10. Write a program that asks the user for a three-digit number, finds the sum of the digits of the number, and then prints both the number and its digit sum.