Pages

20.8.11

Exercises on Section 5

Exercise 12

Give a full description of a function (using the infix notation ×) corresponding to multiplication of integers.

Answer

Solution

A suitable description of integer multiplication is given below.
function (infix) (x × y on Int) return in Int
pre   true.
post   The returned value is the result of multiplying x and y.

Exercise 13

With n = 966, evaluate each of:
(a) MOD(n, 10);
(b) DIV (n, 10);
(c) MOD(DIV (n, 10), 10).

Answer

Solution

966 = 96 × 10 + 6. So (a) MOD(966, 10) = 6 (the remainder when 966 is divided by 10), and (b) DIV (966,10) = 96. Then (c) MOD(DIV (966, 10), 10) becomes MOD(96, 10). This evaluates to 6, which is the remainder when 96 is divided by 10.

Exercise 14

The function LAST is described below.
function LAST(s in SeqOfX ) return in X
pre   s is not empty.
post   The returned value is the last element in s. For example, LAST([1, 2, 3]) = 3.
Consider the expression NOT(LAST(s) = Char LAST (t)).
  • (a) What is the value of this expression if s is “the” and t is:
    • (i) “same”;
    • (ii) “different”?
  • (b) Under what circumstances does this expression have the value true?
  • (c) Is this expression valid with s = [1,2] and t = [1,8,4,2]?

Answer

Solution

(a) If s = “the” then LAST(s) = ‘e’. (i) With t = “same”, we have LAST(t) = ‘e’, and the given expression becomes
NOT(‘e’ =Char ‘e’) = NOT (true) = false.
(i) With t = “different”, we have LAST(t) = ‘t’, and the given expression becomes
NOT(‘e’ =Char ‘t’) = NOT (false) = true.
(b) The given expression is true if the strings s and t have different last letters.
(c) With these values of s and t, the given expression becomes NOT(2 =Char 2). Now =Char compares two characters, and 2 is an integer. So this expression is not valid. (For the given expression to be valid, we need s and t to be sequences of characters, and to be non-empty, so that the precondition of LAST is satisfied.)

No comments:

Post a Comment